【发布时间】:2021-06-23 08:39:45
【问题描述】:
我没有找到任何具体的信息,这不是一个真正的问题,但我想更好地了解这里发生了什么。
基本上,我正在测试一些简单的 NodeJS 代码,如下所示:
//Summary : Open a file , write to the file, delete the file.
let fs = require('fs');
fs.open('mynewfile.txt' , 'w' , function(err,file){
if(err) throw err;
console.log('Created file!')
})
fs.appendFile('mynewfile.txt' , 'Depois de ter criado este ficheiro com o fs.open, acrescentei-lhe data com o fs.appendFile' , function(err){
if (err) throw err;
console.log('Added text to the file.')
})
fs.unlink('mynewfile.txt', function(err){
if (err) throw err;
console.log('File deleted!')
})
console.log(__dirname);
我以为这段代码会按照从上到下的顺序执行,但是当我查看终端时,我不确定是否是这种情况,因为这是我得到的:
$ node FileSystem.js
C:\Users\Simon\OneDrive\Desktop\Portfolio\Learning Projects\NodeJS_Tutorial
Created file!
File deleted!
Added text to the file.
//Expected order would be: Create file, add text to file , delete file , log dirname.
最终,当我查看我的文件夹时,代码顺序似乎仍以某种方式被遵循,因为该文件已被删除,而我的目录中没有任何内容。
所以,我想知道,为什么终端没有按照代码从上到下编写的顺序登录。 这是 NodeJS 异步特性的结果还是其他原因?
【问题讨论】:
-
基本上,是的。您需要使用
then或async await来确保正确的顺序。如果您的用例非常基础,您可以改用sync functions 或fs-sync库。
标签: node.js asynchronous console.log