#programming
#web development
#nodejs

How to Create a Json Files in Node.js?

Anonymous

AnonymousOct 07, 2023

Here's a basic Node.js script that generates single JSON file:

Source Code

import fs from 'fs'
const fileName = `example.json`
const jsonData = `{
    "Title": "This is title for your page",
    "Meta": "This is meta description for your page",
    "H1": "This is h1 for your page",
    "H2": "This is h2 for you page"
}
`
fs.writeFileSync("./pages/" + fileName, jsonData);

Ouput:

pages/example.json

{
    "Title": "This is title for your page",
    "Meta": "This is meta description for your page",
    "H1": "This is h1 for your page",
    "H2": "This is h2 for you page"
}

If you want to generate multiple JSON files in a Node.js script, you can use a loop to create. Here's an example of how you can modify the script to generate multiple JSON files:

Source Code

import fs from 'fs'
let noOfpages = [1, 2, 3, 4, 5]
for (let i = 0; i < noOfpages.length; i++) {
  const num = noOfpages[i];
  const mdFileName = `data-${num}.json`
  const jsonData = `{
    "Title": "This is title for your page",
    "Meta": "This is meta description for your page",
    "H1": "This is h1 for your page",
    "H2": "This is h2 for you page"
}
`
  fs.writeFileSync("./pages/" + mdFileName, jsonData)
}

In this example, we're using the built-in fs module in Node.js to create a Markdown files.

Next, In this example, Each file has a name that includes a page number, such as "data-1.json," "data-2.json," and so on. these files are stored in a folder called "pages" . you can change the file name and folder name as needed.

You can also update json data.

Finally, we use the fs.writeFile() method to write the Markdown content to the file.

To run this script, save it to a file with a .js extension (e.g., generateJSON.js), and execute it using Node.js:

node generateJSON.js

Ouput:

example

Happy Coding! ❤️