此代码用于附加数据并将其发送到客户端。但数据并没有被追加。请帮助
app.post('/api/display', (req,res) => {
let data = "";
const bod = req.body;
var input = fs.createReadStream('sample.txt');
var r1 = require('readline').createInterface({
input: input
});
r1.on('line', function(line) {
var ar = line.split("=");
var valuetypestring = ar[0].split(" ");
var valuetype = valuetypestring[0];
var valuestring = ar[1].split(" ");
var value = valuestring[1];
for(var attributename in bod){
if(valuetype==attributename){
//console.log is giving the output
console.log(`${valuetype}:${value} new value:${bod[attributename]}`);
//The data doesnt get appended
data+=`${valuetype}:${value} new value:${bod[attributename]}`;
}
}
});
res.send(data); //Here the string is sent empty
});
Readline与许多其他模块一样,是异步的。这意味着它在等待数据时不会阻止代码的执行。因此,您开始侦听一条线路,但没有等待数据发送完成才能调用res.send(data)
。你想做的是更改线路:
res.send(data);
至
r1.on("close", function() {
res.send(data);
});
这样你就知道数据已经收到了。然后,当您从控制台输入数据时,可以按Ctrl+D
表示所有行都已发送。如果您只想接收一行,那么不需要等待close
事件,只需将res.send(data)
移动到行处理程序中即可。