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

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

当前回答

用ejs代替jade

npm 安装 EJS

app.js

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

/线路/ index.js

exports.index = function(req, res){
res.render('index', { title: 'ejs' });};

其他回答

https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906

这是我简单的演示代码主机静态HTML文件使用Express服务器!

希望对你有所帮助!

// simple express server for HTML pages! // ES6 style const express = require('express'); const fs = require('fs'); const hostname = '127.0.0.1'; const port = 3000; const app = express(); let cache = [];// Array is OK! cache[0] = fs.readFileSync( __dirname + '/index.html'); cache[1] = fs.readFileSync( __dirname + '/views/testview.html'); app.get('/', (req, res) => { res.setHeader('Content-Type', 'text/html'); res.send( cache[0] ); }); app.get('/test', (req, res) => { res.setHeader('Content-Type', 'text/html'); res.send( cache[1] ); }); app.listen(port, () => { console.log(` Server is running at http://${hostname}:${port}/ Server hostname ${hostname} is listening on port ${port}! `); });

您可以使用fs对象手动回显文件,但我建议使用ExpressJS框架使您的工作更容易。

...但如果你坚持用艰难的方式来做:

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

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

用ejs代替jade

npm 安装 EJS

app.js

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

/线路/ index.js

exports.index = function(req, res){
res.render('index', { title: 'ejs' });};
   var http = require('http');
   var fs = require('fs');

  http.createServer(function(request, response) {  
    response.writeHeader(200, {"Content-Type": "text/html"});  
    var readSream = fs.createReadStream('index.html','utf8')
    readSream.pipe(response);
  }).listen(3000);

 console.log("server is running on port number ");