簡體   English   中英

異步節點文件創建

[英]Async node file creation

我正在嘗試檢查文件是否存在,如果不存在,請創建文件。

self.checkFeedbackFile = function() {
        // attempt to read the file - if it does not exist, create the file
        var feedbackFile = fs.readFile('feedback.log', function (err, data) {
            console.log("Checking that the file exists.");
        });
        if (feedbackFile === undefined) {
            console.log("File does not exist. Creating a new file...");
        }
    }

我顯然對Node非常陌生。 在Ruby中工作了一段時間,而我對Javascript的了解很少,所以回調和異步執行的概念對我來說很陌生。

現在,我的控制台返回以下內容:

File does not exist. Creating a new file...
Sat Sep 29 2018 12:59:12 GMT-0400 (Eastern Daylight Time): Node server started on 127.0.0.1:3333 ...
Checking that the file exists.

除了不確定如何執行此操作外,為什么ELI5對控制台日志為什么打印順序混亂的解釋是什么?

在您的情況下,將fs.readFile()方法。 它等待io完成。 但是, checkFeedbackFile()方法繼續執行if語句。 建議您使用fs.stat檢查文件是否存在。 fs.writeFileSync以同步方式寫入文件。

self.checkFeedbackFile = function() {
        // attempt to read the file - if it does not exist, create the file
        fs.stat('feedback.log', function(err, data){
            if(err){
                console.log("File doesnt exist, creating a new file");
                //Do Something
                fs.writeFileSync('feedback.log',data);
            }
        }

    }

Node.js是asycn,如果您來自C或Java,那么您已經習慣了:

function main(){
   1();
   2();
   3();
}

在C或Java中,僅當1()完成時,控件才會移至2() Node依賴於1()所做的事情不是這種情況,如果它以異步方式執行任何操作(例如IO),則2()將在1()完成之前執行,因此您會看到異步方法采用了回調,相關功能完成后即可執行。

建議您看一下Nodes Event循環的工作方式。

好。 在主要功能中,您有兩個console.logs。

console.log("Checking that the file exists."); 在回調中。 Ë

但是

console.log("File does not exist. Creating a new file..."); 

只是在if塊內。 所以先炒

因為console.log("Checking that the file exists."); 代碼取決於readfile函數的調用。 您將其包裝在回調中,並作為readfile的第二個參數。 一種讀取文件的操作完成后,將觸發回調結果。 readfile函數處於同一級別的所有其他代碼將被執行,就像readfile函數已經完成了執行一樣。 調用readfile不會阻止此后所有其他代碼的執行,因為您提供了一些回調,這些回調將在操作完成后執行。

此行為與同步編程的行為不同。

console.log('first');
console.log('second');
setTimeout(function(){
    console.log('third');
}, 2000);
console.log('Fourth');

在上面同步編程中提供的代碼中,執行將逐行執行。 要記錄third文本。 執行將等待2秒鍾,但是在非阻塞編程(異步)中,將在執行console.log('third');之前打印出Fourth文本console.log('third');

暫無
暫無

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

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