Node.JS缓冲区后面有一个换行符

如何从这段代码中删除换行符?

socket.on('data', function(data){ console.log('Data in server, sending to handle()'); worker.handle(data, socket); }); 

Worker.handle():

 exports.handle = function handle(command, socket) { console.log('Data sent to handle()'); command = command.toString(); 

的console.log(命令);

编辑:

我得到这个输出:

 test data [newline] 

编辑2:

这是继续的代码:

 if (command === 'look') { //stuff } if (command === 'login') { //stuff 

这不是一个显示/演示问题。 这是与数据传输协议有关的问题。 Socket是一个面向stream的协议,意味着它不是基于消息的。 同时,你正在使用它,就像它是基于消息 – 你可以做,但是你需要为你的发送者和接收者定义一个协议来标识每条消息的开始和结束。

说了这个,根据你的要求,我假设你已经决定使用一个换行符(或一个变体)作为你的消息结束标记。 为了使其正常工作,您需要主动在传入数据中查找换行符,以便在处理之前识别每条消息的结尾并将其去掉。

下面的代码应该replace你的socket.on方法来得到你想要的结果。

 // define your terminator for easy reference, changes var msgTerminator = '\n'; // create a place to accumulate your messages even if they come in pieces var buf; socket.on('data', function(data){ // add new data to your buffer buf += data; // see if there is one or more complete messages if (buf.indexOf(msgTerminator) >= 0) { // slice up the buffer into messages var msgs = data.split(msgTerminator); for (var i = 0; i < msgs.length - 2; ++i) { // walk through each message in order var msg = msgs[i]; // pick off the current message console.log('Data in server, sending to handle()'); // send only the current message to your handler worker.handle(msg, socket); } buf = msgs[msgs.length - 1]; // put back any partial message into your buffer } }); 

你可以使用util.print([…]) ,但是请注意,这是一个同步函数,在输出到stdout会被阻塞。

util.print([…])

同步输出function。 将阻止该进程,将每个参数转换为一个string,然后输出到标准输出。 在每个参数之后不放置换行符。

编辑

或者,您可以使用process.stdout.write() : http : //nodejs.org/api/process.html#process_process_stdout