我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
当前回答
这是对默罕默德·奈斯温的回答的更新
在快车4号。x, sendfile已弃用,必须使用sendfile函数。区别在于sendfile采用相对路径,而sendfile采用绝对路径。因此,__dirname被用来避免硬编码路径。
var express = require('express');
var app = express();
var path = require("path");
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/folder_name/filename.html'));
});
其他回答
你也可以使用这个片段:
var app = require("express");
app.get('/', function(req,res){
res.sendFile(__dirname+'./dir/yourfile.html')
});
app.listen(3000);
这可能会更好一些,因为您将流式文件而不是像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);
您可以使用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);
增加另一个选项-基于例外的答案。
打字稿:
import { Injectable } from '@nestjs/common';
import { parse } from 'node-html-parser';
import * as fs from 'fs';
import * as path from 'path'
@Injectable()
export class HtmlParserService {
getDocument(id: string): string {
const htmlRAW = fs.readFileSync(
path.join(__dirname, "../assets/files/some_file.html"),
"utf8"
);
const parsedHtml = parse(htmlRAW);
const className = '.'+id;
//Debug
//console.log(parsedHtml.querySelectorAll(className));
return parsedHtml.querySelectorAll(className).toString();
}
}
(*)上面的例子是使用nestjs和node-html-parser。
简单的方法是,把你所有的文件,包括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的快速实例,我们正在为访问所有资源的公共目录提供地址。 希望这能有所帮助!