如何加入/拆分对象实际上是一个对象


var ipRegex = require('ip-port-regex');
...
for(var i = 0; i < orgArrayWithHostsAndPorts.length; i++) {
   ipPort = ipRegex.parts(orgArrayWithHostsAndPorts[i]);
   console.log(ipPort);
   /* 
     Gives long listing
     { ip: 'firstip', port: 'firstport' }
     { ip: 'secondip', port: 'secondport' }
    */
   fs.writeFileSync('/tmp/test.json', JSON.stringify(ipPort, null, 2), 'utf-8');
}

所以当我做fs.writeFileSync时,我只看到第一个对象。我真正想要的是将每个IP/端口保存为数组中的单独对象集。我不能将,添加到每个对象

fs.writeFileSync方法每次调用文件都会覆盖该文件。由于您要为列表中的每个项目调用一次,因此只有一个项目同时在文件中。

此外,使用fs.appendFileSync会写入所有对象,使您的文件看起来像:

{ "ip": "firstip", "port": "firstport" }
{ "ip": "secondip", "port": "secondport" }

但这不是有效的.json。对象必须包含在数组中,并由逗号分隔:

[
    { "ip": "firstip", "port": "firstport" },
    { "ip": "secondip", "port": "secondport" }
]

我想到的最简单的方法是将您想要的结果映射到新数组中,然后将该数组写入文件:

ipPorts = orgArrayWithHostsAndPorts.map( data => ipRegex.parts(data));
fs.writeFileSync('/tmp/test.json', JSON.stringify(ipPorts, null, 2), 'utf-8');

该文件以写入模式打开,因此您在每个执行for循环时都在覆盖。更好的方法是在附加模式下打开文件并写入内容。查看如何附加到节点中的文件?

相关内容

最新更新