0

我正在尝试编写读取文件的代码,计算其中的行数,然后在开头添加另一行,该行的编号。基本上就像一个索引。问题是 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

在此处输入图像描述

4

2 回答 2

0

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

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);
        });

    });
}
于 2019-12-05T19:43:30.087 回答
0

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

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

因此,类似于以下内容:

const readFileData = fs.readFileSync("list.txt");

fs.appendFileSync('list.txt', '[' + lines + ']' + item + '\n');

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

于 2019-12-05T19:40:33.637 回答