gpt4 book ai didi

node.js - 生产环境动态生成 Express 路由失败

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:44 25 4
gpt4 key购买 nike

我见过很多人在他们的routes/index.js 中动态生成所有路由,如下所示:

require("fs").readdirSync("./routes", 'utf8').forEach(function(file) {
if (file != 'index.js' && file != '.DS_Store') {
require("./"+file);
}
});

这在开发中效果很好,但在生产中则不然。如果我删除它并手动添加路由,它就可以正常工作。有什么想法吗?

如果您认为这有帮助,这是我的错误:

node.js:134

throw e; // process.nextTick error, or 'error' event on first tick

Error: ENOENT, No such file or directory './routes'
at Object.readdirSync (fs.js:376:18)
at Object.<anonymous> (/app/routes/index.js:4:15)
at Module._compile (module.js:402:26)
at Object..js (module.js:408:10)
at Module.load (module.js:334:31)
at Function._load (module.js:293:12)
at require (module.js:346:19)
at Object.<anonymous> (/app/server.js:50:14)
at Module._compile (module.js:402:26)
at Object..js (module.js:408:10)
Process died with exit code 1. Restarting...

最佳答案

正如 Mark Bessey 在他的回答中所说,您正在从当前目录解析 routes 目录 - 与主脚本所在的位置无关。您可能应该使用__dirname。来自 the docs :

The name of the directory that the currently executing script resides in.

fs.readdirSync(path.join(__dirname, "routes"))

此外,您不需要传递'utf8'。另外,在代码中使用任何 Sync 函数时要非常小心 - 一般来说,在服务器开始接受请求之前,在顶级范围内是可以的,所以应该没问题在这种情况下。

关于node.js - 生产环境动态生成 Express 路由失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10459291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com