【问题标题】:Read from file in nodejs and display it从nodejs中的文件读取并显示它
【发布时间】:2013-07-09 14:01:02
【问题描述】:

当我在本地运行我的 nodejs 代码时,它运行良好。我得到了想要的输出。

我的代码:

var fs = require("fs");
fs.readFile("index.html", function (err, data) {
    if (err) throw err;
    console.log(data.toString());
});

本地运行时

  • index.html 包含“来自 index.html 的 Hello World”,并且位于同一目录中。

问题:
当我尝试在 heroku 上部署 web.js(包含与上面相同的代码)时,它似乎不起作用。
我希望在 heroku 上部署“Hello World from index.html”时显示它。

执行以下命令

git push heroku master之后

这里是 heroku URL 显示的内容

背景:我使用的是 AWS Ubuntu 12.04,我的 github 存储库是 this,其中包含所需的 web.js 文件。我正在使用 Cygwin。

可能有什么问题。我是 nodejs 的新手,所以我想我在这里遗漏了一些非常基本的东西。如果您是专家,请善意回答这个愚蠢的问题。从字面上看,我整晚都想弄清楚。 我想要的只是从 index.html 文件中读取并在部署到 Heroku 时在“http://nameless-headland-9348.herokuapp.com/”上显示它包含的文本。

【问题讨论】:

    标签: node.js heroku github


    【解决方案1】:

    您是否阅读并尝试了 Node.js 的 Heroku getting started guide?您没有提供任何日志,因此很难诊断您的问题,但是您的最后一个代码 sn-p 有一个明显的问题 - 它侦听端口 8080。您应该侦听 Heroku 提供给您的端口号(再次参见文档),使用类似这样的东西来检索它process.env.PORT

    【讨论】:

    • 到底是什么问题?
    • 问题是我的端口设置为 8080 而不是 process.env.PORT
    【解决方案2】:

    您正在尝试引用文件 index.html 并使用相对路径。这可能不适用于heroku,它会尝试从其他地方加载文件。

    所以你想要的是相对于你的 app.js 加载它是:

    fs.readFile(path.join(process.cwd(), 'index.html'), function(err, data) {
    

    它所要做的(你的代码)就是控制台记录你的东西。虽然没有 http 服务器和任何东西,但您正试图通过浏览器访问它。没有任何服务器作为响应。

    请阅读此答案,以了解如何通过 http:Nodejs send file in response 发送文件

    【讨论】:

    • 我是 nodejs 新手,这就是你的意思吗? var http = require('http'); var fs = require("fs"); http.createServer(function(request,response){ fs.readFile(path.join(process.cwd(), 'index.html'), function(err, data) { if (err) return console.log(err); console.log(data.toString()); }).listen(8080); }); 没看懂http服务器怎么用。
    猜你喜欢
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多