Terminé reemplazando todo '$' en el archivo con '$' y haciendo lo siguiente:
await fsPromises.writeFile( targetFilePath, compiledSourceFile({ schemaName: schema.schema_name }).replace('$', '$', 'ig') );Tengo un archivo simple con los siguientes contenidos:
const { executeQuery } = require('../../db'); const getAllTableRecords = async ({ tableName }) => executeQuery({ query: ` SELECT *, '${tableName}' as "table_name" FROM <%= schemaName %>.${tableName} `, }); module.exports = { getAllTableRecords, };Intento leer este archivo mediante programación y enviarlo a un directorio diferente:
import path from 'path'; import { promises as fsPromises } from 'fs'; import { template } from 'lodash'; const sourceFilePath = path.join(__dirname, 'utils', 'index.js'); const compiledSourceFile = template(sourceFile); const targetFilePath = path.resolve(__dirname, 'temp', 'utils', 'index.js'); const [sourceFile] = await Promise.all([ fsPromises.readFile(sourceFilePath, 'utf-8'), fsPromises.mkdir(targetFilePath, { recursive: true }) ]); await fsPromises.writeFile(targetFilePath, compiledSourceFile({ schemaName: schema.schema_name }));Todo lo que hace es leer el archivo de plantilla, reemplazar los valores en la plantilla y crear y escribir recursivamente en el destino de destino.
Pero esto arroja un error,
ReferenceError: tableName is not defined Parece que lodash.template no puede procesar el literal de plantilla ${} . Sigue fallando en esta línea,
SELECT *, '${tableName}' as "table_name" ^^^^^^^^^^^^^^¿Cuáles son mis opciones aquí si quiero ceñirme a los literales de plantilla?