【问题标题】:appendFile() runs before readFile() even though appendFile() is chronologically after the readFile()appendFile() 在 readFile() 之前运行,即使 appendFile() 按时间顺序在 readFile() 之后
【发布时间】:2020-03-30 19:08:27
【问题描述】:

我正在尝试编写代码来读取一个文件,计算其中的行数,然后在开头添加另一行,该行的编号。基本上就像一个索引。问题是 fs.appendFile() 在 fs.readFile() 完成之前开始运行,但我不确定为什么。有什么我做错了吗?

我的代码:

fs.readFile('list.txt', 'utf-8', (err, data) => {
    if (err) throw err;

    lines = data.split(/\r\n|\r|\n/).length - 1;

    console.log("Im supposed to run first");

});
console.log("Im supposed to run second");


fs.appendFile('list.txt', '[' + lines + ']' + item + '\n', function(err) {
    if (err) throw err;
    console.log('List updated!');

    fs.readFile('list.txt', 'utf-8', (err, data) => {
        if (err) throw err;

        // Converting Raw Buffer dto text 
        // data using tostring function. 
        message.channel.send('List was updated successfully! New list: \n' + data.toString());
        console.log(data);
    });

});

我的输出:

Im supposed to run second
List updated!
Im supposed to run first
[0]first item

【问题讨论】:

    标签: javascript file console readfile appendfile


    【解决方案1】:

    目前,您使用的是readFileappendFile。这两个函数都是异步的,会同时运行,一旦完成就返回。

    如果您想同步运行这些文件,可以使用fs.readFileSyncfs.appendFileSync 方法同步读取并附加到文件。

    因此,类似于以下内容:

    const readFileData = fs.readFileSync("list.txt");
    
    fs.appendFileSync('list.txt', '[' + lines + ']' + item + '\n');
    

    第一行代码将运行,然后是第二行代码。

    【讨论】:

      【解决方案2】:

      您使用的函数是异步的,所以第二个函数的响应可以在第一个函数的响应之前收到。

      fs.readFile('list.txt', 'utf-8', (err, data) => {
          if (err) throw err;
      
          lines = data.split(/\r\n|\r|\n/).length - 1;
      
          console.log("Im supposed to run first");
          appendFile(lines);
      
      });
      
      
      let appendFile = (lines)=> {
          fs.appendFile('list.txt', '[' + lines + ']' + item + '\n', function(err) {
              console.log("Im supposed to run second");
              if (err) throw err;
              console.log('List updated!');
      
              fs.readFile('list.txt', 'utf-8', (err, data) => {
                  if (err) throw err;
      
                  // Converting Raw Buffer dto text 
                  // data using tostring function. 
                  message.channel.send('List was updated successfully! New list: \n' + data.toString());
                  console.log(data);
              });
      
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-10
        • 1970-01-01
        • 1970-01-01
        • 2013-03-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-22
        • 2012-03-20
        相关资源
        最近更新 更多