Writing JSON object to a JSON file with fs.writeFileSync Writing JSON object to a JSON file with fs.writeFileSync json json

Writing JSON object to a JSON file with fs.writeFileSync


You need to stringify the object.

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output));


I don't think you should use the synchronous approach, asynchronously writing data to a file is better also stringify the output if it's an object.

Note: If output is a string, then specify the encoding and remember the flag options as well.:

const fs = require('fs');const content = JSON.stringify(output);fs.writeFile('/tmp/phraseFreqs.json', content, 'utf8', function (err) {    if (err) {        return console.log(err);    }    console.log("The file was saved!");}); 

Added Synchronous method of writing data to a file, but please consider your use case. Asynchronous vs synchronous execution, what does it really mean?

const fs = require('fs');const content = JSON.stringify(output);fs.writeFileSync('/tmp/phraseFreqs.json', content);


Make the json human readable by passing a third argument to stringify:

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output, null, 4));