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

标签 node.js express

我见过很多人在他们的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/

相关文章:

javascript - nodejs如何将父对象的范围限定为mysql查询匿名回调

node.js - 适用于容器的 Azure Web 应用程序未设置环境变量

node.js - 重定向到另一个 html 页面

node.js - 如何在express中重定向到post请求

node.js - 我们如何使用 mongoose 和 expressjs-nodejs 对 mongodb 中的 ObjectId 列进行排序?

node.js - 操作数据对象sequelize ORM (nodejs)

node.js - 我无法让 Electron 在 Electron 中运行以在 WSL2 Ubuntu 20.04 中运行

node.js - 使用 Express.Router() 具有特定中间件的快速路由

node.js - NodeJS + Redis + Express + Passport Facebook 身份验证失败

javascript - 计算 grunt 观看的文件数