簡體   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