如何使用Node.js运行HTML文件

51

我有一个带有AngularJS的简单HTML页面,如下所示:

    //Application name
    var app = angular.module("myTmoApppdl", []);

    app.controller("myCtrl", function ($scope) {
        //Sample login function
        $scope.signin = function () {
            var formData =
                    {
                        email: $scope.email,
                        password: $scope.password
                    };
        console.log("Form data is:" + JSON.stringify(formData));
    };
});

HTML文件:

<html>
    <head>
        <link href="bootstrap.min.css" rel="stylesheet" type="text/css"/>
    </head>

    <body ng-app="myTmoApppdl" ng-controller="myCtrl">
        <div class="container">
            <div class="form-group">
                <form class="form" role="form" method="post" ng-submit="signin()">
                    <div class="form-group col-md-6">
                        <label class="">Email address</label>
                        <input type="email" class="form-control" ng-model="email" id="exampleInputEmail2" placeholder="Email address" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label class="">Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword2" ng-model="password" placeholder="Password" required>
                    </div>
                </form>
                <button type="submit" class="btn btn-primary btn-block">Sign in</button>
            </div>
        </div>
    </body>

    <script src="angular.min.js" type="text/javascript"></script>

    <!--User defined JS files-->
    <script src="app.js" type="text/javascript"></script>
    <script src="jsonParsingService.js" type="text/javascript"></script>
</html>

我是Node.js的新手。我已经在我的系统中安装了Node.js服务器,但我不确定如何使用Node.js运行一个简单的HTML文件?


实际上,即使在您的桌面上复制/粘贴此代码,它也会运行。 - daniel
1
你不能使用Node.js“运行HTML文件”。Node.js是用于开发服务器端Web应用程序的JavaScript环境。HTML文件通常由Web浏览器运行。 - Leonid Beschastny
Node.js不会“运行”HTML文件。你可能只需要一个提供静态文件服务的服务器。 - SLaks
11个回答

50

您可以使用内置的nodejs Web服务器。

例如,添加文件 server.js 并放置以下代码:

var http = require('http');
var fs = require('fs');

const PORT=8080; 

fs.readFile('./index.html', function (err, html) {

    if (err) throw err;    

    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(PORT);
});

在控制台中使用命令 node server.js 启动服务器后,您的 index.html 页面将在 URL http://localhost:8080 上可用。


我需要将它添加到HTML的脚本标签中吗? - kittu
@Satyadev 不管你如何称呼这个文件,它都是服务器端的责任。 - Alexandr
我遇到了这样的错误:2 'require' was used before it was defined. var http = require('http'); 5 Expected an identifier and instead saw 'const'. const PORT=8080; 5 Stopping. (26% scanned). const PORT=8080; - kittu
它只是打印“它工作了!路径命中:/index.htm” - kittu
没问题,我使用这个 Stack Overflow 的帖子解决了问题:https://dev59.com/8m025IYBdhLWcg3wT0Lq - kittu
显示剩余2条评论

33

只需全局安装http-server

npm install -g http-server

无论在何处,只要需要运行HTML文件,请运行命令http-server 例如:您的HTML文件在/home/project/index.html中 你可以执行/home/project/$ http-server

这将为您提供访问网页的链接: http-server Starting up http-server, serving ./ Available on: http://127.0.0.1:8080 http://192.168.0.106:8080


1
这可能是最直接的,不是吗? - Sergei Wallace
我认为这不是一个好的解决方案。当可以避免时,您不应该全局安装npm包。整个Node基础设施已经明确地远离将-g添加到所有内容中。 - Raydot
我尝试安装http-server时没有使用-g选项,但是当我尝试启动服务器时,Node会报错。看来在安装这个特定的包时仍然需要使用-g选项。 - shieldgenerator7
安装全局需要sudo权限,所以我在项目目录中没有使用-g选项进行安装。然后,我通过运行node_modules/http-server/bin/http-server来作为项目目录中的index.html文件的服务器。 - tash
实际上,我遇到了一个问题——如何将它变成守护进程?在上述方法中,它会在 shell 上运行。因此,除非我使用像 screen 这样的应用程序或能够永远保持我的 shell 打开,否则服务器会在某个时刻被切断。 - tash

18

我也曾遇到过这样的情况,需要在nodejs中运行一个web应用,其中index.html是入口点。这是我所做的:

  • 在应用程序的根目录中运行 node init(这将创建一个package.json文件)
  • 在应用程序的根目录中安装express: npm install --save express (save会更新package.json中的express依赖)
  • 在应用程序的根目录中创建一个public文件夹,并放置您的入口点文件(index.html)和所有相关的文件(这仅是为了简化操作,在大型应用程序中可能不是一个好的方法)。
  • 在应用程序的根目录中创建一个server.js文件,在其中我们将使用node的express模块来从当前目录下提供public文件夹服务。
  • server.js

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public')); //__dir and not _dir
var port = 8000; // you can use any port
app.listen(port);
console.log('server on' + port);
  • 执行node server命令:它应该输出“server on 8000”

  • 启动http://localhost:8000/:将会调用你的index.html文件

  • 文件结构类似于上图


    我发现了比我的更好的解决方案:https://dev59.com/8m025IYBdhLWcg3wT0Lq?noredirect=1&lq=1 请查看Tony的答案并点赞。 - TylerDurden
    我实际上更喜欢你的回答。它快速简便,并且使用了本地的Node功能,而不需要安装过多的包。 - jean d'arme

    11

    将您的HTML文件移动到名为“www”的文件夹中。创建一个名为“server.js”的文件,并编写以下代码:

    var express = require('express');
    var app = express();
    
    app.use(express.static(__dirname + '/www'));
    
    app.listen('3000');
    console.log('working on 3000');
    

    创建文件后,运行命令 "node server.js"。

    1
    这是我见过的最简单的配置,而且非常好用 :) - Irfan Raza
    找不到模块 'express'。 - MindRoasterMir
    1
    @MindRoasterMir 这是因为express是一个包/框架。你需要先将其添加到你的package.json中-- npm install express等等。更多信息请参见另一个问题。相比于http,它使用起来要容易得多,特别是如果你想为你的html文件提供CSS和其他相关的包含文件。 - ruffin
    npm install --save express 是一个先决条件。 - abhi

    7
    最简单的命令为: npx http-server 这需要在执行此命令的目录中存在一个 index.html 文件。
    Vijaya Simha 已经提到过这个方法,但我认为使用 npx 更加简洁和方便。我已经用这种方法运行了几个月的 web 服务器。
    文档:https://www.npmjs.com/package/http-server

    它能运行,但不在我期望的端口上,请问如何分配自定义端口?谢谢。 - Aljohn Yamaro
    @AljohnYamaro npx http-server -p 8080 - codepleb

    5

    通过HTTP访问并获取在8080端口上提供的HTML文件:

    >npm install -g http-server
    
    >http-server
    

    如果你有公共文件夹(./public/index.html),它将成为你的服务器根目录,如果没有,那么会成为你运行服务器时所在的文件夹。你可以将该文件夹作为参数发送,例如:
    http-server [path] [options]
    

    期望的结果:

    *> 启动 http-server,提供 ./public。 可从以下位置访问:

    http://LOCALIP:8080

    http://127.0.0.1:8080

    按 CTRL-C 停止服务器

    http-server 已停止.*

    现在,可以运行: http://localhost:8080

    将打开 ./public 文件夹中的 index.html

    参考文献: https://www.npmjs.com/package/http-server


    2
    这是一个简单的html文件“demo.htm”,存储在与node.js文件相同的文件夹中。
    <!DOCTYPE html>
    <html>
      <body>
        <h1>Heading</h1>
        <p>Paragraph.</p>
      </body>
    </html>
    

    以下是调用此html文件的node.js文件。
    请注意:保留HTML标签。
    var http = require('http');
    var fs = require('fs');
    
    var server = http.createServer(function(req, resp){
      // Print the name of the file for which request is made.
      console.log("Request for demo file received.");
      fs.readFile("Documents/nodejs/demo.html",function(error, data){
        if (error) {
          resp.writeHead(404);
          resp.write('Contents you are looking for-not found');
          resp.end();
        }  else {
          resp.writeHead(200, {
            'Content-Type': 'text/html'
          });
          resp.write(data.toString());
          resp.end();
        }
      });
    });
    
    server.listen(8081, '127.0.0.1');
    
    console.log('Server running at http://127.0.0.1:8081/');
    

    在命令提示符中启动上述的Node.js文件,会显示消息“Server running at http://127.0.0.1:8081/”。现在,在您的浏览器中输入“http://127.0.0.1:8081/demo.html”。


    你的代码缩进和空格很混乱,难以阅读。请纠正它们,以便未来的读者更容易理解。 - Adam Barnes

    1

    无论是使用框架还是自己编写nodejs服务器。

    一个简单的文件服务器可能如下所示:

    import * as http from 'http';
    import * as url from 'url';
    import * as fs from 'fs';
    import * as path from 'path';
    
    var mimeTypes = {
         "html": "text/html",
         "jpeg": "image/jpeg",
         "jpg": "image/jpeg",
         "png": "image/png",
         "js": "text/javascript",
         "css": "text/css"};
    
    http.createServer((request, response)=>{
        var pathname = url.parse(request.url).pathname;
        var filename : string;
        if(pathname === "/"){
            filename = "index.html";
        }
        else
            filename = path.join(process.cwd(), pathname);
    
        try{
            fs.accessSync(filename, fs.F_OK);
            var fileStream = fs.createReadStream(filename);
            var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
            response.writeHead(200, {'Content-Type':mimeType});
            fileStream.pipe(response);
        }
        catch(e) {
                console.log('File not exists: ' + filename);
                response.writeHead(404, {'Content-Type': 'text/plain'});
                response.write('404 Not Found\n');
                response.end();
                return;
        }
        return;
        }
    }).listen(5000);
    

    @SLaks 不错,我不知道这个包。顺便说一句,我发布的代码只是我的调试版本。正式版本只包含一个 server.js 文件。 - Matthias
    @Matthias,我按照@JILeXanDR发布的另一个答案进行了操作,但运行后只打印出It Works!! Path Hit: /index.htm。您能告诉我哪里做错了吗? - kittu
    1
    您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Matthias
    你可以用 require 语句替换 import 语句。并保存这段代码。在 server.js 文件中也要进行修改。 - Matthias

    1
    为了通过Node JS项目部署HTML页面,例如部署一个Angular构建文件,在这种情况下,所有请求都需要重定向到index.html,我们可以使用Node JS的通配符路由来提供Angular项目,但我们需要确保Angular路由和Node JS API路由没有命名冲突。

    app.js

    //Angular App Hosting Production Build
    app.use(express.static(__dirname + '/dist/ShoppingCart'));
    
    // For all GET requests, send back index.html (PathLocationStrategy) (Refresh Error)
    app.get('*', (req,res) => {
      res.sendFile(path.join(__dirname, '/dist/ShoppingCart/index.html'));
    });
    
    

    1
    app.get('/home', (req, res) => {
        res.sendFile(__dirname + '/home.html');
    });
    

    1
    这个回答在“低质量回答队列”中,可能会被投票删除。我建议您尝试扩展内容细节,以避免发生这种情况。 - moken
    虽然这段代码可能回答了问题,但我建议你还是提供一下代码的解释以及它是如何解决问题的。带有解释的答案通常更有帮助和质量更高,并且更有可能获得赞同。 - Mark Rotteveel

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接