我试图找出如何加载和呈现一个基本的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 ");

其他回答

你可以直接在end方法中加载HTML

response.end('...<p>blahblahblah</p>...')

这和

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

你也可以使用这个片段:

var app = require("express");
app.get('/', function(req,res){
   res.sendFile(__dirname+'./dir/yourfile.html')
});
app.listen(3000);

如果你使用管道,它就非常简单。下面是server.js的代码片段。

Var HTTP = require(' HTTP '); Var fs = require('fs'); 函数onRequest(req, res){ 日志("用户提出请求。“+ req.url); res.writeHead(200, {'Content-Type': 'text/html'}); var readStream = fs. varcreatererestream (__dirname + '/index.html','utf8'); /*包含你的HTML文件和目录名,而不是<<__dirname + '/index.html'>>*/ readStream.pipe (res); } http.createServer (onRequest) .listen (7000); console.log('Web服务器正在运行…');

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

简单的方法是,把你所有的文件,包括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的快速实例,我们正在为访问所有资源的公共目录提供地址。 希望这能有所帮助!