天天看点

html 中加入node.js,在Node.js中加载基本HTML

在Node.js中加载基本HTML

这里只是一个简单的Node.js noob问题。 我试图找出如何加载和“显示”一个基本的HTML文件,所以我不必编写像response.write('...

blahblahblah

...');这样的代码。

David Granado asked 2019-04-03T04:08:54Z

18个解决方案

215 votes

我刚刚找到了一种使用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);

});

基本概念只是原始文件读取和转储内容。 但仍然对更清洁的选择开放!

David Granado answered 2019-04-03T04:09:12Z

35 votes

您可以使用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);

Stephen answered 2019-04-03T04:09:44Z

32 votes

使用app.get获取html文件。 这很简单!!

const express = require('express');

const app = new express();

app.get('/', function(request, response){

response.sendfile('yourhtmlpagename.html');

});

就这么简单。为此使用快递模块。安装快递:npm install express -g

Muhammed Neswine answered 2019-04-03T04:10:16Z

21 votes

我知道这是一个老问题,但是没有人提到它,我认为值得添加:

如果你真的想要提供静态内容(例如'about'页面,图像,css等),你可以使用静态内容服务模块之一,例如node-static。 (还有其他一些可能更好/更差 - 尝试search.npmjs.org。)通过一些预处理,您可以从静态过滤动态页面并将它们发送到正确的请求处理程序。

Paul answered 2019-04-03T04:10:49Z

18 votes

这可能是更好的一些,因为你将流式传输文件而不是像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);

user2428926 answered 2019-04-03T04:11:14Z

11 votes

这是对Muhammed Neswine的回答的更新

在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'));

});

Mit Mehta answered 2019-04-03T04:11:47Z

8 votes

我学到的最好的方法是使用快递和html文件作为快递提供了很多优势。 如果你愿意,你也可以将它扩展到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");

干净,最好.. !!!

Kaushik Ray answered 2019-04-03T04:12:19Z

8 votes

它使用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...');

Devsullo answered 2019-04-03T04:12:45Z

6 votes

简单的方法是将所有文件(包括index.html或所有资源,如CSS,JS等)放在公共文件夹中,或者您可以随意命名,现在您可以使用快速js并告诉应用程序 使用_dirname作为:

在你的server.js中使用express添加这些

var express = require('express');

var app = express();

app.use(express.static(__dirname + '/public'));

如果你想让单独的目录在公共目录下添加新目录并使用该路径“/ public / Your DirName”

那么我们在这做什么呢?我们正在创建名为app的express实例,如果公共目录访问所有资源,我们正在给地址。希望这可以帮助 !

Muaaz salagar answered 2019-04-03T04:13:32Z

5 votes

使用快递模块怎么样?

var app = require('express')();

app.get('/',function(request,response){

response.sendFile(__dirname+'/XXX.html');

});

app.listen('8000');

然后,您可以使用浏览器获取/ localhost:8000

李杰駿 answered 2019-04-03T04:14:06Z

4 votes

我认为这将是一个更好的选择,因为它显示运行服务器的URL:

var http = require('http'),

fs = require('fs');

const hostname = '';

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}/`);

})

});

sghazagh answered 2019-04-03T04:14:33Z

3 votes

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 ");

Siddharth Shukla answered 2019-04-03T04:14:52Z

2 votes

我知道这是一个老问题 - 如果您不想使用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')

}

})

}

user548 answered 2019-04-03T04:15:17Z

2 votes

使用ejs而不是玉

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' });};

Saurabh Chandra Patel answered 2019-04-03T04:16:02Z

1 votes

这是一个非常古老的问题......但如果您的用例是在临时的基础上将特定的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);

granmoe answered 2019-04-03T04:16:28Z

1 votes

您还可以使用此代码段:

var app = require("express");

app.get('/', function(req,res){

res.sendFile(__dirname+'./dir/yourfile.html')

});

app.listen(3000);

user9474032 answered 2019-04-03T04:16:53Z

0 votes

我们可以加载带有连接框架工作的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框架的原因。

Balayesu Chilakalapudi answered 2019-04-03T04:17:34Z

0 votes

[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}!

`);

});

xgqfrms answered 2019-04-03T04:18:20Z