简体   繁体   English

使用fs.writeFile将javascript代码写入js

[英]Write javascript code into a js using fs.writeFile

I'm trying to write JavaScript code into a js with Nodejs fs module. 我正在尝试使用Nodejs fs模块将JavaScript代码写入js。 I managed to write a json file but could wrap my head around on how to write JavaScript to it. 我设法编写了一个json文件,但可以全神贯注于如何向其中编写JavaScript。

 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 我需要使用以下数据创建一个.js文件

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

module.exports = cricketers ;

use string templating 使用字符串模板

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

Where yourArray is an array of objects 其中yourArray是对象数组

Two things: 两件事情:

  1. If all you want to do is to be able to do let someData = require('someFile.json'); 如果您要做的就是能够let someData = require('someFile.json'); Nodejs already supports requiring json files and treats them like Js objects. Node.js已经支持需要json文件,并将它们像Js对象一样对待。
  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. fs.writeFile函数采用字符串,因此您只需要生成要写入文件的字符串即可。

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. 显然,这仅适用于非常特定的用例,但要点是,可以通过简单(或复杂的...)字符串操作来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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