This question already has answers here:
Node.js, can't open files. Error: ENOENT, stat './path/to/file'
                            
                                (2个答案)
                            
                    
                6个月前关闭。
        

    

这是一个菜鸟问题。我正在尝试使用tunnel-ssh访问我的数据库。如果我独立运行function createTunnelToMongoDB,则连接正常。当我从app()运行它时,它在配置内返回错误no such file or directory, open '../../id_rsa'。我认为问题与model.exports有关。有人可以告诉我为什么我不能这样做吗?

路径:app.js

(async function app() {
  try {
    // create a tunnel
    const tunnel = await createTunnelToMongoDB();
  } catch (e) {
    console.log("our error", e);
  }
})();


路径:createTunnelToMongoDB.js

var config = {
  username: "root",
  privateKey: require("fs").readFileSync("../../id_rsa"),
  ...etc
};
var tnl = tunnel(config, function(error, tnl) {
  if (error) {
    console.log(error);
  }
  return tnl;
});

module.exports = tnl;

最佳答案

readFileSync的路径是相对于工作目录的。如果要使其相对于模块,则必须将其与__dirname结合在一起,是包含该模块的目录的路径:

var fs = require("fs");
var path = require("path");

var config = {
  username: "root",
  privateKey: fs.readFileSync(path.join(__dirname, "../../id_rsa")),
  ...etc
};

关于javascript - 从app.js执行时,函数中的Config无法找到文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58828927/

10-12 12:20
查看更多