在 Node.js 中加载基本 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4720343/
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-29 06:13:12  来源:igfitidea点击:

Loading basic HTML in Node.js

htmlnode.js

提问by David Granado

I'm trying to find out how to load and render a basic HTML file so I don't have to write code like:

我试图找出如何加载和呈现一个基本的 HTML 文件,这样我就不必编写如下代码:

response.write('...<p>blahblahblah</p>...');

回答by David Granado

I just found oneway using the fs library. I'm not certain if it's the cleanest though.

我刚刚找到了一种使用fs 库的方法。我不确定它是否是最干净的。

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


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

The basic concept is just raw file reading and dumping the contents. Still open to cleaner options, though!

基本概念只是原始文件读取和转储内容。不过,仍然对更清洁的选择持开放态度!

回答by Muhammed Neswine

use app.get to get the html file. its simple!!

使用 app.get 获取 html 文件。这很简单!!

const express = require('express');
const app = new express();

app.get('/', function(request, response){
    response.sendFile('absolutePathToYour/htmlPage.html');
});

its as simple as that. For this use express module. Install express: npm install express -g

就这么简单。为此,请使用 express 模块。安装快递:npm install express -g

回答by Stephen

You can echo files manually using the fs object, but I'd recommend using the ExpressJSframework to make your life much easier.

您可以使用 fs 对象手动回显文件,但我建议使用ExpressJS框架让您的生活更轻松。

...But if you insist on doing it the hard way:

...但如果你坚持以艰难的方式去做:

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

http.createServer(function(req, res){
    fs.readFile('test.html',function (err, data){
        res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
        res.write(data);
        res.end();
    });
}).listen(8000);

回答by Paul

I know this is an old question, but as no one has mentioned it I thought it was worth adding:

我知道这是一个老问题,但由于没有人提到它,我认为值得补充:

If you literally want to serve static content (say an 'about' page, image, css, etc) you can use one of the static content serving modules, for example node-static. (There's others that may be better/worse - try search.npmjs.org.) With a little bit of pre-processing you can then filter dynamic pages from static and send them to the right request handler.

如果您确实想要提供静态内容(例如“关于”页面、图像、CSS 等),您可以使用静态内容服务模块之一,例如 node-static。(还有其他可能更好/更糟 - 尝试 search.npmjs.org。)通过一些预处理,您可以从静态中过滤动态页面并将它们发送到正确的请求处理程序。

回答by user2428926

This would probably be some what better since you will be streaming the file(s) rather than loading it all into memory like fs.readFile.

这可能会更好一些,因为您将流式传输文件而不是像 fs.readFile 那样将其全部加载到内存中。

var http = require('http');
var fs = require('fs');
var path = require('path');
var ext = /[\w\d_-]+\.[\w\d]+$/;

http.createServer(function(req, res){
    if (req.url === '/') {
        res.writeHead(200, {'Content-Type': 'text/html'});
        fs.createReadStream('index.html').pipe(res);
    } else if (ext.test(req.url)) {
        fs.exists(path.join(__dirname, req.url), function (exists) {
            if (exists) {
                res.writeHead(200, {'Content-Type': 'text/html'});
                fs.createReadStream('index.html').pipe(res);
            } else {
                res.writeHead(404, {'Content-Type': 'text/html'});
                fs.createReadStream('404.html').pipe(res);
        });
    } else {
        //  add a RESTful service
    }
}).listen(8000);

回答by Mit Mehta

This is an update to Muhammed Neswine's answer

这是对穆罕默德·内斯温的回答的更新

In Express 4.x, sendfile has been deprecated and sendFilefunction has to be used. The difference is sendfile takes relative path and sendFile takes absolute path. So, __dirname is used to avoid hardcoding the path.

在 Express 4.x 中,sendfile 已被弃用,必须使用sendFile函数。区别是sendfile 取相对路径,sendFile 取绝对路径。因此,__dirname 用于避免对路径进行硬编码。

var express = require('express');
var app = express();
var path = require("path");

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/folder_name/filename.html'));
});

回答by Devsullo

It's more flexible and simple way to use pipemethod.

它是更灵活和简单的使用pipe方法。

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

http.createServer(function(request, response) {
  response.writeHead(200, {'Content-Type': 'text/html'});

  var file = fs.createReadStream('index.html');
  file.pipe(response);

}).listen(8080);

console.log('listening on port 8080...');

回答by Kaushik Ray

Best way i learnt is using express with html files as express gives lots of advantage. Also you can extend it to a Heroku platform if you want..Just saying :)

我学到的最好的方法是使用带有 html 文件的 express,因为 express 有很多优势。如果你愿意,你也可以将它扩展到 Heroku 平台..只是说:)

var express = require("express");
var app     = express();
var path    = require("path");


app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
});

app.listen(3000);



console.log("Running at Port 3000");

Clean and best..!!!

干净,最好..!!!

回答by Muaaz salagar

The easy way to do is, put all your files including index.html or something with all resources such as CSS, JS etc. in a folder public or you can name it whatever you want and now you can use express js and just tell app to use the _dirname as :

最简单的方法是,将所有文件(包括 index.html 或包含所有资源(如 CSS、JS 等)的文件)放在 public 文件夹中,或者您可以随意命名它,现在您可以使用 express js 并告诉 app使用 _dirname 作为:

In your server.js using express add these

在你的 server.js 中使用 express 添加这些

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));

and if you want to have seprate directory add new dir under public directory and use that path "/public/YourDirName"

如果你想有单独的目录在公共目录下添加新目录并使用该路径“/public/YourDirName”

SO what we are doing here exactly? we are creating express instance named app and we are giving the adress if the public directory to access all the resources. Hope this helps !

那么我们到底在做什么呢?我们正在创建名为 app 的快速实例,如果公共目录访问所有资源,我们将提供地址。希望这可以帮助 !

回答by u4848934

How about using express module?

使用 express 模块怎么样?

    var app = require('express')();

    app.get('/',function(request,response){
       response.sendFile(__dirname+'/XXX.html');
    });

    app.listen('8000');

then, you can use browser to get /localhost:8000

然后,您可以使用浏览器获取 /localhost:8000