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

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

当前回答

我知道这是一个老问题,但由于没有人提到过,我认为有必要补充一下:

如果你真的想要提供静态内容(比如一个“关于”页面,图像,css等),你可以使用一个静态内容服务模块,例如node-static。(还有其他可能更好或更差的方法——试试search.npmjs.org。)通过一点点预处理,您就可以从静态页面中过滤动态页面,并将它们发送到正确的请求处理程序。

其他回答

使用快递模块怎么样?

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

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

    app.listen('8000');

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

您可以使用Express使用Node加载和呈现基本的HTML文件。这大约需要10分钟才能开始。它被绑定到http.createServer(),所以你仍然在Node的土地上,可以轻松地删除它。

// app.js
const path = require('path');
const express = require('express');

const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', express.static('index.html'));
app.use('/test', express.static('test.html'));

module.exports = app;

// server.js
const http = require('http');
const PORT = process.env.PORT || 3000;

const appServer = require('./app');
const httpServer = http.createServer(appServer);

httpServer.listen(PORT);
console.log(`Listening on port ${PORT}...`);

这可能会更好一些,因为您将流式文件而不是像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);

我知道这是一个老问题,但由于没有人提到过,我认为有必要补充一下:

如果你真的想要提供静态内容(比如一个“关于”页面,图像,css等),你可以使用一个静态内容服务模块,例如node-static。(还有其他可能更好或更差的方法——试试search.npmjs.org。)通过一点点预处理,您就可以从静态页面中过滤动态页面,并将它们发送到正确的请求处理程序。

var http = require('http');
var fs = require('fs');            //required to readfile

http.createServer(function(req, response){
    fs.readFile('index.html',function (err, data){
        response.writeHead(200);
        response.write(data);
        response.end();
    });
}).listen(8000);
//   #just use express lol

Index.html是HTML文件的名称