I've found various answers to this on Stack Overflow and elsewhere.
Should I do this:
let data = fs.readFileSync(FILE_NAME, "utf8");
Or this:
let data = fs.readFileSync(FILE_NAME, {encoding: "utf8"});
?
I've found various answers to this on Stack Overflow and elsewhere.
Should I do this:
let data = fs.readFileSync(FILE_NAME, "utf8");
Or this:
let data = fs.readFileSync(FILE_NAME, {encoding: "utf8"});
?
Share Improve this question edited Jul 6, 2020 at 20:50 halfer 20.4k19 gold badges108 silver badges201 bronze badges asked May 19, 2018 at 11:48 goodvibrationgoodvibration 6,2064 gold badges34 silver badges67 bronze badges 4- Consider reading docs first, please: nodejs/api/fs.html#fs_fs_readfile_path_options_callback – Kumar Shubham Commented May 19, 2018 at 12:03
- 4 @KumarShubham: I have asked this question after reading the doc which you've linked. The exact answer to my question is not there, which is why I have asked it. Consider reading a question carefully before you suggest material which doesn't answer it!!! – goodvibration Commented May 19, 2018 at 12:05
- The accepted answer gives straight reference from docs, Anyways, not your fault. Sorry :), It happens sometimes. – Kumar Shubham Commented May 19, 2018 at 15:21
-
I guess the short answer is
Use 'utf8' when you don't need e.g. flags
– kungfooman Commented Nov 11, 2021 at 9:02
2 Answers
Reset to default 14From the documentation, both are valid:
fs.readFileSync(path[, options])
- options <Object> | <string>
- encoding <string> | <null> Default: null
- flag <string> See support of file system flags. Default: 'r'.
The second argument may be either an options object, or an encoding name.
I don't think you need to mention encoding explicitly,since it is an optional parameter
var fs = require("fs");
/***
* implementation of readFileSync
*/
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
/***
* implementation of readFile
*/
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
this worked even without providing "encoding" argument