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

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

当前回答

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

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

其他回答

试试这个:

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。如果你愿意,你可以添加更多。

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

如果你真的想要提供静态内容(比如一个“关于”页面,图像,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

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

简单的方法是,把你所有的文件,包括index.html或所有资源,如CSS, JS等,在一个文件夹公共或你可以命名它任何你想要的,现在你可以使用express JS,只是告诉app使用_dirname as:

在你的server.js中使用express添加这些

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));

如果你想有一个单独的目录,在公共目录下添加新的目录,并使用“/public/YourDirName”路径

我们到底在这里做什么? 我们正在创建名为app的快速实例,我们正在为访问所有资源的公共目录提供地址。 希望这能有所帮助!