nodejs异步案例

时间:2021-02-11 05:46:37
const fs = require('fs');

fs.readFile('./test.txt', 'utf-8', (err, data) => {
err
? console.error(err)
: console.log(data.toString()+'1');
});
console.log("over1"); fs.readFile('./test.txt', 'utf-8', (err, data) => {
setTimeout(() => {
err
? console.error(err)
: console.log(data.toString()+'2');
}, 100);
});
console.log("over2"); fs.readFile('./test.txt', 'utf-8', (err, data) => {
err
? console.error(err)
: console.log(data.toString()+'3');
});
console.log("over3"); var data = fs.readFileSync('./test.txt');
console.log(data.toString()+'4');
console.log("over4"); /*------------------------
输出结果如下
over1
over2
over3
hello node dkplus!4
over4
hello node dkplus!1
hello node dkplus!3
hello node dkplus!2
------------------------*/