在字符串中使用forEach



我试图使用fs为ESM(ECMAScript)做一个命令处理程序,因为你不能在ESM中使用fs,我有2个js环境,一个是ESM,一个是Node.js, Node env只在那里,所以它读取文件夹的所有文件名,并使用这些名称在另一个env使用的文件中导入和导出它们。我已经有了它所以名称被存储在节点env的const中但是当我试图用fs写它们时它会给我一个错误,当我试图记录字符串时它说未定义

const fs = require("fs")
const commands = []
try {
fs.unlinkSync("./scripts/modules/commands.js")
console.log('x1b[32m File Deleted Succesfully x1b[0m')
} catch (e) {
console.error(e)
}
try {
fs.openSync("./scripts/modules/commands.js", 'w')
console.log('x1b[32m Created File Successfully')
} catch (e) {
console.error(e)
}
try {
const cCommands = fs.readdirSync("./scripts/modules/commands/").filter(file => file.endsWith('.js'));
for (const file of cCommands) {
const name = file.replace(".js", "")
commands.push(name)
}
console.log('x1b[32m Pushed all Files Successfully x1b[0mn')
} catch (e) {
console.error(e)
}
// This outputs => 'ping' as a string
console.log(`${commands}`)
// This outputs => undefinedexport const commands = {undefined}; but should output => import {ping} from './commands/ping'; export const commands = {ping:ping};
console.log(`${commands.forEach(command => `import {${command}} from './commands/${command}';`)}export const commands = {${commands.forEach(command => `${command}:${command},`)}};`)
try {
const cmdString = `${commands.forEach(command => `import {${command}} from './commands/${command}';`)}export const commands = {${commands.forEach(command => `${command}:${command},`)}};`
const jsonString = JSON.stringify(cmdString);
fs.writeFile("./scripts/modules/commands.js", jsonString)
console.log(jsonString)
console.log('x1b[32m Send all Commands Successfully x1b[0m')
} catch (e) {
console.error(e)
}

编辑:将所有的。foreach()函数更改为。map(),现在这个错误发生了=>TypeError [ERR_INVALID_ARG_TYPE]: The "参数必须为函数类型。收到未定义的

要修复这个错误,只需使用fs。writeFileSync代替fs.writeFile

最新更新