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

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

当前回答

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

其他回答

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

http.createServer((req, res) => {
    fs.readFile('./' + req.url, (err, data) => {
        if (!err) {
            var dotoffset = req.url.lastIndexOf('.');
            var mimetype = dotoffset == -1 ? 'text/plaint' : {
                '.html': 'text/html',
                '.css': 'text/css',
                '.js': 'text/javascript',
                '.jpg': 'image/jpeg',
                '.png': 'image/png',
                '.ico': 'image/x-icon',
                '.gif': 'image/gif'
            }[ req.url.substr(dotoffset) ];
            res.setHeader('Content-Type', mimetype);
            res.end(data);
            console.log(req.url, mimetype);
        } else {
            console.log('File not fount: ' + req.url);
            res.writeHead(404, "Not Found");
            res.end();
        }
    });
 }).listen(PORT);

有了这个,你可以包括js, css源代码时链接他们,你可以加载图标,imgs, gif。如果你愿意,你可以添加更多。

这是一个相当老的问题……但如果你在这里的用例是简单地向浏览器发送一个特定的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');            //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 app = require('express')();

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

    app.listen('8000');

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