简体   繁体   中英

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"
]

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!");
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM