Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.parse(fs.readFileSync()) returning a buffer - string of numbers

I'm using a simple Node.js to pull information from a valid jsonfile (checked with JSLint), but the code i'm using doesn't return the expected value:

        squadJSON = JSON.parse(fs.readFileSync('./squads/squad' + whichSquad + '.json'));     

and it returns:

{ type: 'Buffer', data:  [ 123,  10,  32,  32,  34,  97,  99,  ... 548 more items ] } 

Any reason as to why this happens?

like image 408
Conrad Scherb Avatar asked Feb 16 '18 00:02

Conrad Scherb


People also ask

Does readFileSync return a buffer?

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

What does readFileSync return?

The readFileSync() function returns a Buffer .

What is readFileSync?

The readFileSync() method will read the content of a file synchronously, so your JavaScript code execution will be stopped until the method is finished. The readFileSync() method accepts two parameters: path - mandatory - which is the relative path to the file you want to read ( string type)


1 Answers

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

https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options

So, tell fs.readFileSync() what encoding to use:

squadJSON = JSON.parse(fs.readFileSync('./squads/squad' + whichSquad + '.json', 'utf8'));  
like image 55
Sidney Avatar answered Sep 28 '22 10:09

Sidney