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 ;
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 ;
Share
Improve this question
asked Jun 2, 2019 at 18:07
TRomeshTRomesh
4,4818 gold badges49 silver badges78 bronze badges
2 Answers
Reset to default 6Two things:
- 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. - 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 plicated...) string manipulation.
use string templating
const data = `const cricketers = ${JSON.stringify(yourArray)};
module.exports = cricketers;
`
Where yourArray
is an array of objects