繁体   English   中英

如何使用 node.js 运行 html 文件

[英]How to run html file using node js

我有一个简单的 html 页面,其中包含 angular js,如下所示:

    //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 文件?

您可以使用内置的 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上可用

只需全局安装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

我也遇到过这样的情况,我必须在 nodejs 中运行一个 web 应用程序,以 index.html 作为入口点。 这是我所做的:

  • 在应用程序的根目录中运行node init (这将创建一个 package.json 文件)
  • 在应用程序的根目录中安装 express : npm install --save express (保存将使用 express 依赖项更新 package.json)
  • 在您的应用程序的根目录中创建一个公共文件夹,并放置您的入口点文件 (index.html) 及其所有相关文件(这只是为了简化,在大型应用程序中这可能不是一个好方法)。
  • 在应用程序的根目录中创建一个server.js文件,我们将在其中使用节点的 express 模块,它将为当前目录中的公共文件夹提供服务。
  • 服务器.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 :它应该输出“8000上的服务器”

  • 启动http://localhost:8000/ :您的 index.html 将被调用

文件结构将是类似的东西

将您的 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”

迄今为止最简单的命令:

npx http-server

这需要在执行此命令的目录中有一个现有的 index.html。

Vijaya Simha 已经提到了这一点,但我认为使用 npx 更简洁、更短。 几个月以来,我一直在使用这种方法运行网络服务器。

文档: https : //www.npmjs.com/package/http-server

http 访问并获取 8080 上的 html 文件:

>npm install -g http-server

>http-server

如果您有 public (./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

要么使用框架,要么使用 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);

这是一个简单的 html 文件“demo.htm”,与 node.js 文件存储在同一文件夹中。

<!DOCTYPE html>
<html>
  <body>
    <h1>Heading</h1>
    <p>Paragraph.</p>
  </body>
</html>

下面是调用这个 html 文件的 node.js 文件。

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/');

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

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

应用程序.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'));
});

const http = require('http');
const fs = require('fs');
var mimeTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "png": "image/png",
    "js": "text/javascript",
    "css": "text/css"
};

var server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.writeHeader(200, { "Content-Type": "text/html" });
        fs.createReadStream('./public/index.html').pipe(res)
    }
    var filesDepences = req.url.match(/\.js|.css/);
    if (filesDepences) {
         var extetion = mimeTypes[filesDepences[0].toString().split('.')[1]];
        res.writeHead(200, { 'Content-Type': extetion });
        fs.createReadStream(__dirname + "/public" + req.url).pipe(res)
    }
})

server.listen(8080);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM