我尝试创建简单的 TCP 服务器来评估并打印结果,但它不起作用,这是我的代码:
var net = require('net');
var server = net.createServer(function(socket) {
socket.on('data', function(data) {
socket.write('result: ');
socket.end(eval(data));
});
});
server.listen(8080);
当我连接到端口 8080 时,我得到了这个:
$ echo 10+10 | nc localhost 8080
result: 10+10
为什么 eval 不起作用?
最佳答案
默认情况下,流在数据事件上接收一个 Buffer
对象。
来自MDN :
If the argument of eval() is not a string, eval() returns the argument unchanged
由于eval
uating对象没有效果,write()
按原样发送数据。您必须将套接字的编码显式设置为 utf8 才能将数据转换为字符串。
var server = net.createServer(function(socket) {
socket.setEncoding('utf8');
socket.on('data', function(data) {
socket.write('result: ');
var evaluatedData = eval(data);
socket.end(evaluatedData.toString());
});
});
toString()
是必需的,因为 socket.write
(实际上是 Writable.write
)接受 string
或缓冲区
。
关于javascript - Node.js TCP 服务器,用于评估和打印数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18285876/