Node.js 异步节点文件创建
我试图检查文件是否存在,如果不存在,则创建文件Node.js 异步节点文件创建,node.js,file,asynchronous,Node.js,File,Asynchronous,我试图检查文件是否存在,如果不存在,则创建文件 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
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...");
}
}
我显然对诺德很陌生。我在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完成。但是,checkfeedbackfle()
方法继续执行if语句。
建议您使用来检查文件是否存在。
并以同步方式写入文件
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()
。节点的情况并非如此,这取决于1()
正在做什么,如果它以异步方式做任何事情,比如IO,那么2()
将在1()
完成之前执行,因此您会看到异步方法执行回调,相关函数完成后将执行回调
我建议你看看它是如何工作的 好的。在main函数中有两个console.log
console.log(“检查文件是否存在”)代码>在回调中。e
但是
console.log("File does not exist. Creating a new file...");
就在if块内。因此它首先被触发,因为console.log(“检查文件是否存在”)代码>代码取决于调用readfile
函数。将其包装在回调函数中,作为readfile
的第二个参数。读取文件的操作完成后,将触发回调并显示结果。与readfile
函数处于同一级别的所有其他代码将被执行,就好像readfile
函数已经完成了它的执行一样。readfile的调用不会阻止随后所有其他代码的执行,因为您提供了一些回调,这些回调将在操作完成时执行
这种行为与同步编程的行为不同
console.log('first');
console.log('second');
setTimeout(function(){
console.log('third');
}, 2000);
console.log('Fourth');
在上面提供的同步编程代码中,执行将逐行进行。记录第三个文本。执行将等待2秒钟,但在非阻塞编程(异步)中,在执行console.log('third')之前,将打印Fourth
文本代码>好的,这很有意义。对不起,那是个愚蠢的问题P将继续修补这个,看看我是否能让它创建文件。好的,我将用这种方式尝试。同步编写文件与异步编写文件的好处是什么?这是可行的,但文件不是马上创建的,我需要它。它最终将以读取流的形式记录输入。fs.writeFileSync()
将等待创建文件。因此,在这行中,如果你输入了读写文件的语句,它们应该可以工作。但是,如果在调用fs.stat()
之后有一些内容,则这些语句可能会在执行fs.stat的回调之前执行。