I have used fs.readFile
and the Sync method fs.readFileSync
the same file as below :
first fs.readFile
give the expect result:
var fs = require('fs');
var path = require('path');
//Normalizing the path for windows environment
var normalPath = path.normalize( __dirname + '/test.txt');
//Reading the test.txt file in Async mode
fs.readFile( normalPath, function(err, data) {
console.log( data.toString() );
});
and fs.readFileSync
that runs with error:
var fs = require('fs');
var path = require('path');
//Normalizing the path for windows environment
var normalPath = path.normalize( __dirname + '/test.txt');
//Reading the test.txt file in Async mode
fs.readFileSync( normalPath, function(err, data) {
console.log( data.toString() );
});
This is the error that I encountered with:
fs.js:40
throw new TypeError('Expected options to be either an object or a string, ' +
^
TypeError: Expected options to be either an object or a string, but got function
instead
at throwOptionsError (fs.js:40:9)
at Object.fs.readFileSync (fs.js:423:5)
at Object.<anonymous> (C:\Users\Arash\Desktop\learnyounode\program.js:8:4)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:140:18)
at node.js:1001:3
readFileSync
will return the data
you're looking for, so instead of:
fs.readFileSync( normalPath, function(err, data) {
console.log( data.toString() );
});
Just do:
var data = fs.readFileSync( normalPath );
@ericmdantas is right. The synchronous methods of fs
return the result (or throw if there is an error). They do not take a callback argument.
notice that i do like so:
var fs = require('fs');
fs.readFile(validFile, 'utf8', (err, data)=> {
if (err) {
throw err;
}
console.log('async readFile');
console.log(data);
});
fs.readFileSync(validFile, 'utf8', (err, data)=> {
if (err) {
throw err;
}
console.log('sync readFile');
console.log(data);
});
The result is the sync version not even logging, like not executed.
IDK if it possible to reproduce it online. I am using v4.2.6
@brutalcrozt that's because there's no callback when you use readFileSync
, you should do:
try {
var data = fs.readFileSync(validFile, 'utf8');
console.log('sync readFile');
console.log(data);
}
catch (e) {
console.log(e);
}
Thanks @ericmdantas that is my bad, stupid while looking the documentation.
No worries :smile:
Most helpful comment
@brutalcrozt that's because there's no callback when you use
readFileSync
, you should do: