Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS function readFileSync - do I pass "utf8" or {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"});

?

like image 575
goodvibration Avatar asked May 19 '18 11:05

goodvibration


People also ask

How does fs readFileSync work?

readFileSync() method is an inbuilt application programming interface of fs module which is used to read the file and return its content. In fs. readFile() method, we can read a file in a non-blocking asynchronous way, but in fs. readFileSync() method, we can read files in a synchronous way, i.e. we are telling node.

What is utf 8 in Node js?

Overview. In this guide, you can learn how to enable or disable the Node. js driver's UTF-8 validation feature. UTF-8 is a character encoding specification that ensures compatibility and consistent presentation across most operating systems, applications, and language character sets.

What does fs readFileSync return?

fs. readFileSync() returns a Buffer if you don't specify an encoding.

How to read a File using fs in Node js?

To include the File System module, use the require() method: var fs = require('fs'); Common use for the File System module: Read files.


1 Answers

From 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.

like image 92
Flimzy Avatar answered Sep 22 '22 12:09

Flimzy