Create/Update JavaScript file/code 使用 Nodejs

Create/Update JavaScript file/code using Nodejs

我需要创建一个 JavaScript 文件,其中应该包含这样的代码。

const students= require('students');
const lecturers = require('lecturers');

const people = [
    {
        name: 'student',
        tag: 'student',
        libName: 'students'
    },
    {
        name: 'lecturer',
        tag: 'lecturer',
        libName: 'lecturers '
    }
]

module.exports = people;

目前我设法使用 nodejs 中的 fs 模块创建了这个文件。像这样

let peoples = {
        name: 'student',
        tag: 'student',
        libName: 'students'
    };

let data = `
   const ${peoples.libName} = require('${peoples.libName}'); 
   const people = [
     ${providers}
   ]
   module.exports = people;
 `;

    fs.writeFile(".pep.config.js", data, function(err) {
      if (err) {
        console.log('Fail')
      }
      console.log('Success')
    });

如何将值(人员对象)添加到人员数组并将要求语句添加到现有文件?。使用当前方法,我一次只能添加一个数据。像这样。

const students= require('students');

const people = [
    {
        name: 'student',
        tag: 'student',
        libName: 'students'
    }
]

module.exports = people;

给定您的设置的最简单方法,恕我直言:使用锚点作为注释来了解数组的边界:

   const providers = [
//ANCHOR_PROVIDERS_START
     ${providers}
//ANCHOR_PROVIDERS_END
   ]

然后更新,类似:

fileContent.replace(
  '//ANCHOR_PROVIDERS_END',
  `,${moreProviders}\n//ANCHOR_PROVIDERS_END`
);

您还可以创建一个函数,使用起始锚点覆盖现有内容。

不过,也许使用 JSON:

更灵活
   const providers = JSON.parse(
     ${providersAsJsonArray}
   );//ANCHOR_PROVIDERS_END

因此您可以检索数组,按照您喜欢的方式对其进行更改,然后像这样将其重新设置到文件中:

fileContent.replace(
  /(const providers = JSON.parse\(\n)(.+)(\n\s*\);\/\/ANCHOR_PROVIDERS_END)/m,
  (match, starting, sjson, closing) => {
    const json = JSON.parse(sjson);
    // do something with json, which represents the existing array
    json.push({ some: 'new', value: 'is now inserted' });
    // inject the new content
    return `${starting}${JSON.stringify(json)}${closing}`;
  }
);

本着这种精神,因为这变得有点乏味,您还可以在邻近的 .json 文件中声明您的数据,然后从您的 .pep.config.js 中读取它以填充您的变量。您甚至可以 require 它,但请注意 requirecache 不会为您提供 JSON.

的过时版本