readFile is executed asynchronously, so data
can only be accessed inside the callback function, if you want it to be synchronous, you should use readFileSync
Async:
'use strict';
const fs = require('fs');
const fileName = 'readme.txt';
fs.readFile(fileName, 'utf8', function (err, data) {
if (err)
return console.log(err);
console.log('result read: ' + data);
});
Sync:
var str = fs.readFileSync(fileName, 'utf8'); // This will block the event loop, not recommended for non-cli programs.
console.log('result read: ' + str);
UPDATE
You can use util.promisify
to convert fs.readFile
from callback API to promise API.
const fs = require('fs');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
(async() => {
try {
const result = await readFile('readme.txt', 'utf8');
consle.log(result);
} catch(e) {
console.error(e);
}
})();
In Node 10 you can use fs/promises
and avoid util.promisify
const fs = require('fs').promises;
(async() => {
try {
const result = await fs.readFile('readme.txt', 'utf8');
consle.log(result);
} catch(e) {
console.error(e);
}
})();