I’m trying to dynamically create a Function in javaScript. Here is my code:
class Server {
// Omitted for brevity
public async method(method: Function, args: any[]) {
const fsp = await import("fs/promises");
const currentMethods: string[] = [];
Object.keys(fsp).forEach((method) => {
currentMethods.push(method);
});
Object.keys(fsp.default).forEach((method) => {
currentMethods.push(method);
});
let matchedType = false;
for (const currentMethod of currentMethods) {
if (method.name === currentMethod) {
matchedType = true;
}
}
if (!matchedType) {
throw new Error("Invalid method");
}
const callMethod = Function(
`"use strict"; async () => {const {${method.name}} = await import("fs/promises"); return await ${method.name}(${JSON.stringify(args).replace("[", "").replace("]", "")});}`
);
const result = await callMethod();
console.log(result);
return result;
}
}
Usage:
const server = new Server();
await server.method(fsp.writeFile, ["temp.txt", "hello world"]);
The code works like this:
- I pass the method I want to use in this case fsp(Node fs/promises).writeFile
- Then I pass the args as an array
- That generates the following code:
"use strict"; async () => {const {writeFile} = await import("fs/promises"); return await writeFile("temp.txt","hello world");}
- Then I call it and it should write the file
However, this does not work and does nothing. How can I fix it.