我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
当前回答
增加另一个选项-基于例外的答案。
打字稿:
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。
其他回答
我学到的最好的方法是在html文件中使用express,因为express有很多优势。如果你想的话,你也可以把它扩展到Heroku平台上。
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.listen(3000);
console.log("Running at Port 3000");
干净而且最好!!
我认为这将是一个更好的选择,因为它显示了运行服务器的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}/`);
})
});
这是一个相当老的问题……但如果你在这里的用例是简单地向浏览器发送一个特定的HTML页面,我会使用像这样简单的东西:
var http = require('http')
, fs = require('fs');
var server = http.createServer(function(req, res){
var stream = fs.createReadStream('test.html');
stream.pipe(res);
});
server.listen(7000);
增加另一个选项-基于例外的答案。
打字稿:
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。
采用管道法是一种更加灵活、简单的方法。
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...');