Home > database >  why nodejs file system read console first then read the file
why nodejs file system read console first then read the file

Time:10-21

I can read the files using nodejs file system:

const fs = require('fs');

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

console.log('hello shawn!')

Why console.log('hello shawn!') read first times then read the console.log(data.toString())?

Is there any other things in file system read data first then read below console?

CodePudding user response:

It is because .readFile is a asynchronous operation. Its last parameter is callback function, which is started after operation is done. I recommend read something about callbacks and event loop.

You can use a synchronous version of function readFileSync or use utils.promisify to convert callback function to promise and use async/await then example.

  • Related