I'm trying to get the following code to work:
'use strict';
var fs = require('fs');
var fileName = 'readme.txt';
var str = fs.readFile(fileName, 'utf8', function (err, data) {
if (err) {
console.log(err);
throw err;
}
return data;
});
console.log('result read: ' + str);
readme.txt:
console.log('working');
I'm trying to display the following:
result read: console.log('working');
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);
}
})();
You're calling an asynchronous function. This means it does not wait to return when called and will, in this case, return undefined.
You can either use the readFileSync method to call it synchronously, or put your console.log
in the callback
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With