Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an array of strings to a JSON file in Javascript?

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"
]
like image 904
abranhe Avatar asked Dec 23 '22 05:12

abranhe


1 Answers

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!");
}); 
like image 137
Anshul Bansal Avatar answered Dec 26 '22 00:12

Anshul Bansal