我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
当前回答
简单的方法是,把你所有的文件,包括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的快速实例,我们正在为访问所有资源的公共目录提供地址。 希望这能有所帮助!
其他回答
这可能会更好一些,因为您将流式文件而不是像fs.readFile那样将其全部加载到内存中。
var http = require('http');
var fs = require('fs');
var path = require('path');
var ext = /[\w\d_-]+\.[\w\d]+$/;
http.createServer(function(req, res){
if (req.url === '/') {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.createReadStream('index.html').pipe(res);
} else if (ext.test(req.url)) {
fs.exists(path.join(__dirname, req.url), function (exists) {
if (exists) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.createReadStream('index.html').pipe(res);
} else {
res.writeHead(404, {'Content-Type': 'text/html'});
fs.createReadStream('404.html').pipe(res);
});
} else {
// add a RESTful service
}
}).listen(8000);
我们可以用连接框架加载HTML文档。 我已经把我的html文档和相关图像放在我的项目的公共文件夹中,下面的代码和节点模块。
//server.js
var http=require('http');
var connect=require('connect');
var app = connect()
.use(connect.logger('dev'))
.use(connect.static('public'))
.use(function(req, res){
res.end('hello world\n');
})
http.createServer(app).listen(3000);
我已经尝试了fs的readFile()方法,但它无法加载图像,这就是为什么我使用了连接框架。
https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906
这是我简单的演示代码主机静态HTML文件使用Express服务器!
希望对你有所帮助!
// simple express server for HTML pages! // ES6 style const express = require('express'); const fs = require('fs'); const hostname = '127.0.0.1'; const port = 3000; const app = express(); let cache = [];// Array is OK! cache[0] = fs.readFileSync( __dirname + '/index.html'); cache[1] = fs.readFileSync( __dirname + '/views/testview.html'); app.get('/', (req, res) => { res.setHeader('Content-Type', 'text/html'); res.send( cache[0] ); }); app.get('/test', (req, res) => { res.setHeader('Content-Type', 'text/html'); res.send( cache[1] ); }); app.listen(port, () => { console.log(` Server is running at http://${hostname}:${port}/ Server hostname ${hostname} is listening on port ${port}! `); });
采用管道法是一种更加灵活、简单的方法。
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 app = require("express");
app.get('/', function(req,res){
res.sendFile(__dirname+'./dir/yourfile.html')
});
app.listen(3000);