Javascript 如何使用节点js运行html文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35995273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:29:21  来源:igfitidea点击:

How to run html file using node js

javascriptangularjsnode.js

提问by Satyadev

I have a simple html page with angular js as follows:

我有一个带有 angular js 的简单 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 file:

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>

I am new to node js. I have installed node js server in my system but I am not sure how to run a simple html file using node js?

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

回答by JILeXanDR

You can use built-in nodejs web server.

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

Add file server.jsfor example and put following code:

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);
});

And after start server from console with command node server.js. Your index.html page will be available on URL http://localhost:8080

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

回答by Vijaya Simha

Just install http-serverglobally

只需全局安装http-server

npm install -g http-server

npm install -g http-server

where ever you need to run a html file run the command http-server For ex: your html file is in /home/project/index.html you can do /home/project/$ http-server

你需要运行 html 文件的地方运行命令 http-server 例如:你的 html 文件在 /home/project/index.html 你可以做 /home/project/$ http-server

That will give you a link to accessyour webpages: http-server Starting up http-server, serving ./ Available on: http://127.0.0.1:8080 http://192.168.0.106:8080

这会给你一个链接来访问你的网页: http-server Starting up http-server, serving ./ Available on: http://127.0.0.1:8080 http://192.168.0.106:8080

回答by TylerDurden

I too faced such scenario where I had to run a web app in nodejs with index.html being the entry point. Here is what I did:

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

  • run node initin root of app (this will create a package.json file)
  • install express in root of app : npm install --save express(save will update package.json with express dependency)
  • create a public folder in root of your app and put your entry point file (index.html) and all its dependent files (this is just for simplification, in large application this might not be a good approach).
  • Create a server.jsfile in root of app where in we will use express module of node which will serve the public folder from its current directory.
  • 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);
    
  • do node server: it should output "server on 8000"

  • start http://localhost:8000/: your index.html will be called

  • 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 将被调用

File Structure would be something similar

文件结构将是类似的东西

回答by Ved Prakash

Move your HTML file in a folder "www". Create a file "server.js" with code :

将您的 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');

After creation of file, run the command "node server.js"

创建文件后,运行命令“node server.js”

回答by codepleb

The simplest command by far:

迄今为止最简单的命令:

npx http-server

npx http-server

This requires an existing index.html at the dir at where this command is being executed.

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

This was already mentioned by Vijaya Simha, but I thought using npx is way cleaner and shorter. I am running a webserver with this approach since months.

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

Docs: https://www.npmjs.com/package/http-server

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

回答by Divyasshree

This is a simple html file "demo.htm" stored in the same folder as the node.js file.

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

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

Below is the node.js file to call this html file.

下面是调用这个 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/');

Intiate the above nodejs file in command prompt and the message "Server running at http://127.0.0.1:8081/" is displayed.Now in your browser type "http://127.0.0.1:8081/demo.html".

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

回答by Matthias

Either you use a framework or you write your own server with nodejs.

要么使用框架,要么使用 nodejs 编写自己的服务器。

A simple fileserver may look like this:

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

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