【问题标题】:Reading and writing to a file inside a forEach only writing the last loop在 forEach 中读取和写入文件仅写入最后一个循环
【发布时间】:2021-03-22 09:39:37
【问题描述】:

我有一个 forEach,我在其中读取数据并将数据写入文件,(不想将其更改为一次全部写入)但它只写入最后一个循环,在此之前它不会写入任何内容。注意(combinedOutput)我正在写入文件,每个循环都会更改,因此它只写入combinedOutput 的最后一个值。这是怎么回事?我需要每次都关闭一个文件吗?

dev_users.forEach((user, i) => {
fs.readFile('name.json', function(err, data) {
      var json = JSON.parse(data);
      json.push(combinedOutput);

      fs.writeFile('name.json', JSON.stringify(json), (err) => {
        if (err) {
          console.log(err);
        }
      });
    });
}

【问题讨论】:

  • 嗯,一种代码味道是您在同步 forEach 循环中执行异步逻辑。
  • @Taplar 啊谢谢你!!!!!!上帝真笨
  • 另外,你为什么一遍又一遍地读写同一个文件。只需累积您想要的数据并一次写入即可。
  • "我不想把它改成一次性写完" - 嗯,这正是你应该做的。你为什么不想这样做?

标签: javascript node.js foreach fs


【解决方案1】:

您正在一个循环中执行两个异步操作,因此它们都将并行运行,而最后一个运行将覆盖其他操作。

我建议你先把要写入的所有数据都积累起来,然后在一次读/写操作中一次全部写入。

您似乎在循环的每次迭代中将combinedOutput 变量附加到数组的末尾,但是您没有显示该变量的来源,因此我们无法显示执行此操作的完整代码,但是一般代码如下所示:

let newData = dev_users.map(user => {
    // create whatever new data you want here and return it
    return something;
});

fs.readFile('name.json', function(err, data) {
    if (err) {
        // handle error
        return;
    }
    try {
        // add new data onto end of existing data
        let existingData = JSON.parse(data);
        existingData.push(...newData);
        fs.writeFile('name.json', JSON.stringify(existingData), (err) => {
            if (err) {
                // handler error
            } else {
                // all done successfully
            }
        });
    } catch(e) {
        // handle error
        return;
    }
});

使用promise接口读写文件,这样会简单一些:

async function writeMyData(dev_users) {
    let newData = dev_users.map(user => {
        // create whatever new data you want here and return it
        return something;
    });
    let existingData = JSON.parse(await fs.promises.readFile('name.json'));
    existingData.push(...newData);
    return fs.promises.writeFile('name.json', JSON.stringify(existingData));
}

writeMyData(dev_users).then(() => {
    console.log("finished successfully");
}).catch(err => {
    console.log(err);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-22
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多