Estoy tratando de generar un archivo .js ejecutando un script de nodo. aquí está mi código.
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');mientras que esto funcionó para archivos .txt que contenían textos simples o códigos no ejecutables como objetos json. se está ejecutando antes de ejecutar la función writeFileSync. entonces los datos que se insertan en el archivo js son
{}¿Cómo podemos generar un archivo js con código de trabajo dentro de él?
Puede ejecutar el código como una cadena creando una función a partir de él mediante el constructor de funciones.
const code = "let x = 100; console.log(x + 1)"; const run = new Function(code); run();Escriba esta cadena en el archivo JS y ejecute el archivo js usando un proceso secundario.
Resolví el problema siguiendo el código.
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);