0

I need to create a JavaScript file which should consist of code like this.

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;

For the time being i managed to create this file using fs module in nodejs. Like this

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')
    });

How can i add values(people objects) to the array of people and add require statements to an existing file?. with the current method i can only add one data at a time. Like this.

const students= require('students');

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

module.exports = people;
2

1 Answer 1

1

The simplest way given your setup, IMHO: use anchors as comments to know the boundaries of your array:

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

Then to update, something like:

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

You can also make a function to overwrite the existing content using the starting anchor.

However, maybe it's more flexible to use JSON:

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

So you can retrieve the array, alter it the way you like, and set it back into the file like so:

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}`;
  }
);

In this spirit, and because this becomes a bit tedious, you can also declare your data in a neighoring .json file, and read it from your .pep.config.js to populate your variable. You can even require it, but then be careful that require's cache doesn't provide you with an outdated version of the JSON.

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

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.