Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript appendFile()在readFile()之前运行,即使appendFile()按时间顺序在readFile()之后_Javascript_File_Console_Readfile_Appendfile - Fatal编程技术网

Javascript appendFile()在readFile()之前运行,即使appendFile()按时间顺序在readFile()之后

Javascript appendFile()在readFile()之前运行,即使appendFile()按时间顺序在readFile()之后,javascript,file,console,readfile,appendfile,Javascript,File,Console,Readfile,Appendfile,我试图编写一段代码,读取一个文件,计算其中的行数,然后在开头添加另一行的行号。基本上就像一个索引。问题是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; cons

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

当前,您正在使用
readFile
appendFile
。这两个函数都是异步的,将同时运行,并在完成时返回

如果要同步运行这些文件,可以使用和方法同步读取并附加到文件

因此,类似以下内容:

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

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

第一行代码将运行,第二行代码将运行。

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

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

    });
}