为什么nodejs文件系统先读取控制台再读取文件

why nodejs file system read console first then read the file

我可以使用 nodejs 文件系统读取文件:

const fs = require('fs');

fs.readFile('./assets/test1.txt', (err, data) => {
    if(err){
        console.log(err)
    }
    console.log(data.toString())
})

console.log('hello shawn!')

为什么console.log('hello shawn!')先读一遍再读console.log(data.toString())

文件系统中是否还有其他东西先读data再读下面console

因为.readFile是一个异步操作。它的最后一个参数是回调函数,在操作完成后启动。我建议阅读一些关于 callbacks and event loop.

的内容

您可以使用同步版本的函数 readFileSync 或使用 utils.promisify 将回调函数转换为 promise 并使用 async/await 然后 example.