arrays - nodejs WriteStream只写入一行

标签 arrays json node.js streamwriter

我试图让我的程序在退出之前将填充有 JSON 数据包的数组的内容写入初始化时指定的文本文件。然而,程序并没有写入整个数组,而是坚持只将单个数据包写入文件,而不是应写入的数百个数据包。我有一个循环遍历数组的 for 循环,并对数组中的每个元素调用stream.write(messageArray[i])。

该数组使用数据报套接字接收到的 JSON 进行填充,并维护最后 80 秒流量的滚动窗口。这意味着该数组将始终只保存最后 80 秒的数据。这是一些代码。我省略了时间转换,因为我知道它有效。

var filename = String(process.argv[2]);
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
var fs = require('fs');
var stream = fs.createWriteStream(filename);
var messageArray= [];

server.on('message', function(message, rinfo){
try{
    messageArray.push(JSON.stringify(JSON.parse(message)));
}
catch(e)
   {console.log(e); console.log(message);}
total++;

});
server.on('listening', function(){
    var address = server.address();
    console.log('server listening on ' + address.address + ':' + address.port);
});
server.bind(5139);

function exitHandler(options, err){
    if(err) console.log(err.stack);
    if(options.exit){

        stream.on('error', function(err){
            console.log(err.stack);
        });
        var i = 0;
        for(i; i< messageArray.length; i++)
                stream.write(messageArray[i] + ",\r\n");
        stream.end();
        process.exit();
    } 
}

process.on('SIGINT', exitHandler.bind(null, {exit:true}));

process.on('uncaughtException', exitHandler.bind(null , {exit:true}));

有人知道问题出在哪里吗?

最佳答案

写入可能会被延迟,并且退出处理程序是同步的,因此进程在调用处理程序后退出 - 可能导致写入永远不会发生。

您应该做的是同步写入文件:

var filename = String(process.argv[2]);
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
var fs = require('fs');
var messageArray= [];

server.on('message', function(message, rinfo){
try{
    messageArray.push(JSON.stringify(JSON.parse(message)));
}
catch(e)
   {console.log(e); console.log(message);}
total++;

});
server.on('listening', function(){
    var address = server.address();
    console.log('server listening on ' + address.address + ':' + address.port);
});
server.bind(5139);

function exitHandler(options, err){
    if(err) console.log(err.stack);
    if(options.exit){
        fs.writeFileSync(filename, messageArray.join(',\r\n'));
        process.exit();
    } 
}

process.on('SIGINT', exitHandler.bind(null, {exit:true}));

process.on('uncaughtException', exitHandler.bind(null , {exit:true}));

关于arrays - nodejs WriteStream只写入一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24394062/

相关文章:

node.js - 如何区分 facebook 评论和从 facebook api 返回的回复?

python - 将数组 reshape 为方形数组Python

javascript - 在 JavaScript 中检查二叉树是否对称

json - json 文件中的 TFS 构建扩展 "VisibleRules"定义

java - 使用 json 参数访问 Java 中的 REST API

regex - Node js Express 框架 - 正则表达式不起作用

node.js - 错误: Cannot read property '_id' of undefined

c++ - 在对象内的数组中设置值

arrays - 为什么哈希表在存储桶的数组上使用链表?

c# - Json 属性作为节点生成