3

I'm trying to write JavaScript code into a js with Nodejs fs module. I managed to write a json file but could wrap my head around on how to write JavaScript to it.

 fs.writeFile("config.json", JSON.stringify({name: 'adman'tag: 'batsman',age: 25}), 'utf8',{ flag: "wx" }, function(err) {
    if (err) {
      return console.log(err);
    }
    console.log("The file was saved!");
  });

I need to create a .js file with the following data

const cricketers = [
    {
        name: 'adman',
        tag: 'batsman',
        age: 25
    },
    // other objects
]

module.exports = cricketers ;

2 Answers 2

6

Two things:

  1. If all you want to do is to be able to do let someData = require('someFile.json'); Nodejs already supports requiring json files and treats them like Js objects.
  2. Otherwise I don't know of a library that will do exactly this for you, BUT...

You can do this yourself. The fs.writeFile function takes a string, so you just have to generate the string you want to write to the file.

let someData = [{name: 'adman', tag: 'batsman', age: 25}];
let jsonData = JSON.stringify(someData);
let codeStr = `const cricketers = ${jsonData}; module.exports = cricketers;`;
fs.writeFile("someFile.js", codeStr, 'utf8',{ flag: "wx" }, function(err) {
  if (err) {
    return console.log(err);
  }
  console.log("The file was saved!");
});

Obviously this only works for a very specific use case, but the point is it can be done with simple (or complicated...) string manipulation.

Sign up to request clarification or add additional context in comments.

Comments

3

use string templating

const data = `const cricketers = ${JSON.stringify(yourArray)};
module.exports = cricketers;
`

Where yourArray is an array of objects

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.