简体   繁体   中英

generate a js file dynamically using fs node

i am trying to generate a.js file by running a node script. here's my code.

const dynamicCode = [
    {
        "ClassCode" : "9620",
        "Rate" : 0.99,
        "IsActive" : "TRUE",
        "StartDate" : "2021-10-19T17:00:00.000-07:00",
        "EndDate" : "9999-12-30T16:00:00.000-08:00"
    },
    {
        "ClassCode" : "0038",
        "Rate" : 12.19,
        "IsActive" : true,
        "StartDate" : "2021-05-31T17:00:00.000-07:00",
        "EndDate" : "9999-12-30T16:00:00.000-08:00"
    }
]

const bdCode = module.exports = {
    async up(db, client) {
      await db.collection('Configuration_Lookup').deleteMany();
      await db.collection('Configuration_Lookup').insertMany(dynamicCode)
    },
  
    async down(db, client) {
      // TODO write the statements to rollback your migration (if possible)
      // Example:
      // await db.collection('albums').updateOne({artist: 'The Beatles'}, {$set: {blacklisted: false}});
    }
  };

fs.writeFileSync("bds.js", JSON.stringify(bdCode, null, 2), 'utf-8');

while this worked for.txt files containing simple texts, or non-executable codes like json objects. it is executing before running the writeFileSync function. so the data inserting into the js file is

{}

how can we generate a js file with working code inside it

You can run the code as a string by creating a function from it using the Function constructor.

 const code = "let x = 100; console.log(x + 1)"; const run = new Function(code); run();

Write this string to the JS file and run the js file using child process.

i solved the issue by following code.

const dynamicCode = [
    {
        "ClassCode" : "9620",
        "Rate" : 0.99,
        "IsActive" : "TRUE",
        "StartDate" : {"$date": "2021-10-19T00:00:00Z"},
        "EndDate" : {"$date": "9999-12-30T23:59:59Z"}
    },
    {
        "ClassCode" : "0038",
        "Rate" : 12.19,
        "IsActive" : true,
        "StartDate" : {"$date": "2021-10-19T00:00:00Z"},
        "EndDate" : {"$date": "9999-12-30T23:59:59Z"}
    }
]

const bdCode = `module.exports = {
    async up(db, client) {
      await db.collection('Configuration_Lookup').deleteMany();
      await db.collection('Configuration_Lookup').insertMany(${JSON.stringify(dynamicCode, null, 2)})
    },
  
    async down(db, client) {
      // TODO write the statements to rollback your migration (if possible)
      // Example:
      // await db.collection('albums').updateOne({artist: 'The Beatles'}, {$set: {blacklisted: false}});
    }
  };`

fs.writeFileSync("bds.js", bdCode);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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