最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Write javascript code into a js using fs.writeFile - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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 plicated...) string manipulation.

use string templating

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

Where yourArray is an array of objects

发布评论

评论列表(0)

  1. 暂无评论