node-websocket-server TypeError:参数必须是字符串

时间:2011-04-22 21:32:51

标签: javascript node.js websocket

我在ubuntu上拖尾/ var / log / logfile,并得到一个TypeError。适用于我当地的Mac机器/var/log/system.log。

命令:

sudo node server.js /var/log/logfile (must be sudo to view this log file

错误:

/npm/node_modules/node-websocket-server/lib/ws/connection.js:290
    var byteLen = Buffer.byteLength(data, 'utf8'),
                         ^
TypeError: Argument must be a string
    at Connection.<anonymous> (/npm/node_modules/node-websocket-server/lib/ws/connection.js:290:26)
    at clientWrite (//npm/node_modules/node-websocket-server/lib/ws/server.js:34:12)
    at /npm/node_modules/node-websocket-server/lib/ws/server.js:99:7
    at Manager.forEach (/npm/node_modules/node-websocket-server/lib/ws/manager.js:125:14)
    at Server.broadcast (npm/node_modules/node-websocket-server/lib/ws/server.js:98:13)
    at Socket.<anonymous> (/npm/server.js:63:11)
    at Socket.emit (events.js:64:17)
    at Socket._onReadable (net.js:677:14)
    at IOWatcher.onReadable [as callback] (net.js:177:10)

代码:

/*
 * server.js
 */

var util   = require('util');
var sys = require("sys");
var ws = require("/npm/node_modules/node-websocket-server");
var spawn = require('child_process').spawn;

var filename = process.ARGV[2];

if (!filename)
  return sys.puts("Usage: node <server.js> <filename>");

var server = ws.createServer({debug: true});

/*
 * After server comes up
 */
server.addListener("listening", function() {
    sys.log("Listening for connections on localhost:9997");
});

/*
 * Define any port
 */
server.listen(9997);

var tail = spawn("tail", ["-f", filename]);
sys.puts("start tailing");

tail.stdout.on("data", function (data) {
    /* 
     * Send data
     */
    server.broadcast(data);
    console.log('' + data);
});

1 个答案:

答案 0 :(得分:3)

目前node-websocket-server只接受字符串形式的数据,而不是Buffers。缓冲区可能在将来被接受,这主要是由于框架的限制以及我不想进行大量缓冲区复制的事实。 (向套接字写出0xFF或0x00似乎是不负责任的。)

另外,尝试:

var tail = spawn('tail', ['-f', filename]);

tail.stdout.setEncoding('utf8')

由于stdout和stderr的流默认为无编码,这意味着数据事件会发出Buffer对象。至于为什么这个在你的mac上运行但在ubuntu上失败,我不确定,但是刚刚做了一个快速测试,我有ubuntu和mac给我缓冲区对象如果我没有专门设置编码流。