【问题标题】:How to use _dirname with a sibling directory如何将 _dirname 与同级目录一起使用
【发布时间】:2016-10-31 21:15:30
【问题描述】:

我的目录是这样设置的:

public 
    pages
       index.html
routers
    route.js

在 route.js 中,我执行以下操作:

router.get('/', function(req, res) {
    res.sendFile("/public/pages/index.html", {"root": __dirname});
});

我得到 Error: ENOENT: no such file or directory, stat 因为服务器正在查看 myproject/routers/public/pages/index.html 而不是 myproject/public/pages/index.html

1) 我如何解决这个问题并让它使用_dirname 找到正确的路径?

2) 如何让我的服务器记住查看 /public/pages/,这样我就不必每次都指定绝对路径?

【问题讨论】:

    标签: javascript node.js rest directory router


    【解决方案1】:

    所以您可能想使用相对位置,对于您的示例,您可以执行以下操作

    var html_location = './public/pages/'; //first method
    var root_location = {  //second method
        root : './public/pages/'
    }
    router.get('/', function(req, res) {
        res.sendFile('index.html', { root : html_location}); //first method
        res.sendFile('index.html', root_location); //second method
    });
    

    所以根:'.'表示您将从运行 main.js / app.js 文件的文件夹开始该位置,并且文件位置与该位置不同。

    【讨论】:

    • 有没有办法让它更整洁,这样我就不必每次都硬编码./public/pages/
    • 是的,你可以做到res.sendFile('index.html', { root : './public/pages/'});
    • 我明白你在问什么,你可以在页面顶部放置一个变量 var html_location = './public/page/' 并在根目录中使用它,甚至将根对象设置在页面顶部跨度>
    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 2021-06-16
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 2021-10-13
    • 1970-01-01
    相关资源
    最近更新 更多