我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
当前回答
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
采用管道法是一种更加灵活、简单的方法。
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...');
我只是发现了一种使用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);
});
基本概念就是读取原始文件并转储内容。不过,仍然有更清洁的选择!
简单的方法是,把你所有的文件,包括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的快速实例,我们正在为访问所有资源的公共目录提供地址。 希望这能有所帮助!
使用app.get获取HTML文件。很简单!
const express = require('express');
const app = express();
app.get('/', function(request, response){
response.sendFile('absolutePathToYour/htmlPage.html');
});
就这么简单。 为此使用快捷模块。 安装express: npm Install -g express