【发布时间】:2011-06-10 20:35:57
【问题描述】:
我正在尝试了解如何加载和呈现基本 HTML 文件,因此我不必编写如下代码:
response.write('...<p>blahblahblah</p>...');
【问题讨论】:
我正在尝试了解如何加载和呈现基本 HTML 文件,因此我不必编写如下代码:
response.write('...<p>blahblahblah</p>...');
【问题讨论】:
我刚刚发现一种方法是使用fs library。我不确定它是否是最干净的。
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);
});
基本概念只是原始文件读取和转储内容。不过,仍然有更清洁的选择!
【讨论】:
sys = require('util') 不需要,因为控制台不会打印任何内容。
fs.readFile 的调用可以放在对http.createServer 的调用中,从而可以处理错误。将 Stephen 的答案与 if (err) { console.log('something bad'); return res.end('Oops! Something bad happened.');} 一起使用 return 语句是新用户可能会忽略的简单事情。
使用 app.get 获取 html 文件。很简单!!
const express = require('express');
const app = new express();
app.get('/', function(request, response){
response.sendFile('absolutePathToYour/htmlPage.html');
});
就这么简单。
为此使用 express 模块。
安装快递:npm install express -g
【讨论】:
express。
var express = require('express'); var app = express();
npm install express --save代替-g
您可以使用 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);
【讨论】:
我知道这是一个老问题,但由于没有人提到它,我认为值得添加:
如果您确实想提供静态内容(比如“关于”页面、图像、css 等),您可以使用静态内容服务模块之一,例如 node-static。 (还有其他可能更好/更差 - 尝试 search.npmjs.org。)通过一些预处理,您可以从静态过滤动态页面并将它们发送到正确的请求处理程序。
【讨论】:
这可能会更好一些,因为您将流式传输文件而不是像 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);
【讨论】:
使用pipe方法更加灵活简单。
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...');
【讨论】:
这是对Muhammed Neswine's answer的更新
在 Express 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'));
});
【讨论】:
我学到的最好方法是使用带有 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");
干净和最好的..!!!
【讨论】:
如果你使用管道,这真的很简单。以下是server.js代码sn-p。
var http = require('http');
var fs = require('fs');
function onRequest(req, res){
console.log("USER MADE A REQUEST. " +req.url);
res.writeHead(200, {'Content-Type': 'text/html'});
var readStream = fs.createReadStream(__dirname + '/index.html','utf8');
/*include your html file and directory name instead of <<__dirname + '/index.html'>>*/
readStream.pipe(res);
}
http.createServer(onRequest).listen(7000);
console.log('Web Server is running...');
【讨论】:
../ 之类的内容。如果除了将__dirname + "/index.html' 更改为__dirname + requestedPageFromHeader 之外什么都不做,我相信生成的代码会有这个漏洞。只要您包含__dirname +,像~ 这样的目录路径字符就可以了 - 如果用户可以确定路径的开始,则还需要检查这些字符。
最简单的方法是,将所有文件,包括 index.html 或包含所有资源(如 CSS、JS 等)的文件放在 public 文件夹中,或者您可以随意命名,现在您可以使用 express js 和只需告诉应用程序使用 _dirname 作为:
在你的 server.js 中使用 express 添加这些
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
如果您想拥有单独的目录,请在公共目录下添加新目录并使用该路径“/public/YourDirName”
那么我们到底在做什么呢? 我们正在创建名为 app 的快速实例,如果公共目录访问所有资源,我们将提供地址。 希望这可以帮助 !
【讨论】:
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 ");
【讨论】:
response.writeHeader(),而是response.writeHead()。
response.writeHeader() 和 response.writeHead() 都有效。
使用 express 模块怎么样?
var app = require('express')();
app.get('/',function(request,response){
response.sendFile(__dirname+'/XXX.html');
});
app.listen('8000');
然后,您可以使用浏览器获取/localhost:8000
【讨论】:
我认为这是一个更好的选择,因为它显示了运行服务器的 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}/`);
})
});
【讨论】:
你也可以使用这个 sn-p:
var app = require("express");
app.get('/', function(req,res){
res.sendFile(__dirname+'./dir/yourfile.html')
});
app.listen(3000);
【讨论】:
我知道这是一个老问题 - 如果您不想使用 connect 或 express,这里有一个简单的文件服务器实用程序;而是http模块。
var fileServer = require('./fileServer');
var http = require('http');
http.createServer(function(req, res) {
var file = __dirname + req.url;
if(req.url === '/') {
// serve index.html on root
file = __dirname + 'index.html'
}
// serve all other files echoed by index.html e.g. style.css
// callback is optional
fileServer(file, req, res, callback);
})
module.exports = function(file, req, res, callback) {
var fs = require('fs')
, ext = require('path').extname(file)
, type = ''
, fileExtensions = {
'html':'text/html',
'css':'text/css',
'js':'text/javascript',
'json':'application/json',
'png':'image/png',
'jpg':'image/jpg',
'wav':'audio/wav'
}
console.log('req '+req.url)
for(var i in fileExtensions) {
if(ext === i) {
type = fileExtensions[i]
break
}
}
fs.exists(file, function(exists) {
if(exists) {
res.writeHead(200, { 'Content-Type': type })
fs.createReadStream(file).pipe(res)
console.log('served '+req.url)
if(callback !== undefined) callback()
} else {
console.log(file,'file dne')
}
})
}
【讨论】:
这是一个很老的问题...但是如果您的用例只是临时将特定的 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);
【讨论】:
使用 ejs 代替 jade
npm install ejs
app.js
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
./routes/index.js
exports.index = function(req, res){
res.render('index', { title: 'ejs' });};
【讨论】:
我们可以使用连接框架加载 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()方法,但是加载图片失败,所以我用了connect框架。
【讨论】:
https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906
这是我使用 Express 服务器托管静态 HTML 文件的简单演示代码!
希望对你有帮助!
// 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}!
`);
});
【讨论】:
添加另一个选项 - 基于例外答案。
对于打字稿:
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 一起使用。
【讨论】:
可以直接在end方法中加载HTML
response.end('...<p>blahblahblah</p>...')
和
一样response.write('...<p>blahblahblah</p>...')
response.end()
【讨论】:
试试这个:
var http = require('http');
var fs = require('fs');
var PORT = 8080;
http.createServer((req, res) => {
fs.readFile('./' + req.url, (err, data) => {
if (!err) {
var dotoffset = req.url.lastIndexOf('.');
var mimetype = dotoffset == -1 ? 'text/plaint' : {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.jpg': 'image/jpeg',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.gif': 'image/gif'
}[ req.url.substr(dotoffset) ];
res.setHeader('Content-Type', mimetype);
res.end(data);
console.log(req.url, mimetype);
} else {
console.log('File not fount: ' + req.url);
res.writeHead(404, "Not Found");
res.end();
}
});
}).listen(PORT);
有了这个,你可以在链接它们时包含 js、css 源代码,你可以加载图标、imgs、gifs。如果需要,您可以添加更多内容。
【讨论】:
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 文件的名称
【讨论】: