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

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

当前回答

我认为这将是一个更好的选择,因为它显示了运行服务器的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}/`);
        })
}); 

其他回答

我只是发现了一种使用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);
});

基本概念就是读取原始文件并转储内容。不过,仍然有更清洁的选择!

您可以使用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);

这是一个相当老的问题……但如果你在这里的用例是简单地向浏览器发送一个特定的HTML页面,我会使用像这样简单的东西:

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

var server = http.createServer(function(req, res){
  var stream = fs.createReadStream('test.html');
  stream.pipe(res);
});
server.listen(7000);
   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 ");

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

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