8

How can I save an array of strings to a JSON file in Node.js:

const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];

example.json

[
  "a",
  "b",
  "c",
  "d",
  "e", 
  "f",
  "g",
  "h"
]
Abraham
  • 8,525
  • 5
  • 47
  • 53
  • You may find https://stackoverflow.com/questions/2496710/writing-files-in-node-js#2497040 useful, using `JSON.stringify` to turn the JSON object into a string (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). – msbit Jul 29 '18 at 06:34

1 Answers1

15

In Node js you can do like this.

const fs = require('fs');
var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const jsonContent = JSON.stringify(alphabet);

fs.writeFile("./alphabet.json", jsonContent, 'utf8', function (err) {
    if (err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 
Anshul Bansal
  • 1,833
  • 1
  • 13
  • 12