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

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

当前回答

增加另一个选项-基于例外的答案。

打字稿:

import { Injectable } from '@nestjs/common';
import { parse } from 'node-html-parser';
import * as fs from 'fs';
import * as path from 'path'


@Injectable()
export class HtmlParserService {


  getDocument(id: string): string {

      const htmlRAW = fs.readFileSync(
          path.join(__dirname, "../assets/files/some_file.html"),
          "utf8"
      );


      const parsedHtml = parse(htmlRAW);
      const className  = '.'+id;
      
      //Debug
      //console.log(parsedHtml.querySelectorAll(className));

      return parsedHtml.querySelectorAll(className).toString();
  }
}

(*)上面的例子是使用nestjs和node-html-parser。

其他回答

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

我认为这将是一个更好的选择,因为它显示了运行服务器的URL:

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

const hostname = '<your_machine_IP>';
const port = 3000;

const html=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, hostname, () => {
            console.log(`Server running at http://${hostname}:${port}/`);
        })
}); 
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文件的名称

采用管道法是一种更加灵活、简单的方法。

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

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

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