簡體   English   中英

appendFile() 在 readFile() 之前運行,即使 appendFile() 按時間順序在 readFile() 之后

[英]appendFile() runs before readFile() even though appendFile() is chronologically after the readFile()

我正在嘗試編寫讀取文件的代碼,計算其中的行數,然后在開頭添加帶有行號的另一行。 基本上就像一個索引。 問題是 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

在此處輸入圖片說明

目前,您正在使用readFileappendFile 這兩個函數都是異步的,將同時運行,一旦完成就返回。

如果你想同步運行這些,你可以使用fs.readFileSyncfs.appendFileSync方法來同步讀取和附加到文件。

因此,類似於以下內容:

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

    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM