กำลังโหลด HTML พื้นฐานใน Node.js


207

ฉันกำลังพยายามหาวิธีโหลดและแสดงไฟล์ HTML พื้นฐานดังนั้นฉันไม่จำเป็นต้องเขียนโค้ดเช่น:

response.write('...<p>blahblahblah</p>...');

คำตอบ:


240

ฉันเพิ่งพบหนึ่งในวิธีการใช้ห้องสมุด 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);
});

แนวคิดพื้นฐานเป็นเพียงการอ่านไฟล์ดิบและทิ้งเนื้อหา ยังคงเปิดให้ตัวเลือกที่สะอาดกว่า!


14
คุณควรใช้ fs.readFileSync ในกรณีของคุณมันจะไม่ดีสำหรับหน้าเว็บที่จะมาเป็นไม่ได้กำหนด แต่ใช่ว่าเป็นวิธีที่ดีในการสร้างเซิร์ฟเวอร์ HTML พื้นฐาน
ทั่วไปเมื่อ

1
sys = require('util')ไม่จำเป็นเนื่องจากไม่มีสิ่งใดพิมพ์อยู่บนคอนโซล
บากูดัน

1
สิ่งนี้จะอ่านไฟล์ทั้งหมดในหน่วยความจำและในทุกคำขอ คุณควรสตรีมไฟล์จากดิสก์แทนการบัฟเฟอร์ มีห้องสมุดคุณภาพดีสำหรับสิ่งนี้เช่นsenchalabs.org/connectและgithub.com/cloudhead/node-static
Drew Noakes

6
ฉันคิดว่ามันควรจะเป็นwriteHead (... )ไม่ใช่writeHeader (... ) ... Node.js response.writeHead ()
Danny Bullis

2
@generalhenry ดีกว่ายังfs.readFileสามารถวางสายในการโทรไปยังhttp.createServerช่วยให้ข้อผิดพลาดที่จะจัดการ คำตอบการใช้งานของสตีเฟ่นกับคำสั่งเป็นสิ่งง่ายๆที่ผู้ใช้ใหม่อาจมองข้าม if (err) { console.log('something bad'); return res.end('Oops! Something bad happened.');}return
eenblam

47

ใช้ app.get เพื่อรับไฟล์ html มันง่าย !!

const express = require('express');
const app = new express();

app.get('/', function(request, response){
    response.sendFile('absolutePathToYour/htmlPage.html');
});

มันง่ายเหมือนที่ สำหรับการใช้โมดูลด่วนนี้ ติดตั้งด่วน:npm install express -g


35
expressคุณลืมที่จะพูดถึงว่าคุณต้องมี
ร้องว้าย

7
express resrecend res.sendfile ด่วน: ใช้ res.sendFile แทนstackoverflow.com/a/26079640/3166417
itzhar

1
คำตอบที่ดี สำหรับผู้ที่ไม่รู้วิธีใช้งานด่วนให้พิมพ์ก่อน app.get .... :var express = require('express'); var app = express();
Eugenijus S.

2
ใช้npm install express --saveแทน -g
MrWater

39

คุณสามารถสะท้อนไฟล์ด้วยตนเองโดยใช้วัตถุ 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);

7
ใช่นั่นเป็นเรื่องเดียวกับที่ฉันคิด ขอบคุณสำหรับคำแนะนำด่วนด้วย มันค่อนข้างหวานและฉันค่อนข้างแน่ใจว่าฉันจะใช้มันสำหรับโครงการต่อไปของฉัน เป้าหมายของฉันคือการคิดออกว่ามันทำภายใต้ประทุนก่อนที่ฉันจะปล่อยให้กรอบทำการยกของหนักสำหรับฉัน
David Granado

1
ไฟร์วอลล์ของโปรแกรมป้องกันไวรัสสามารถปิดใช้งานการย้ายนี้
Mohammad Farahani

22

ฉันรู้ว่านี่เป็นคำถามเก่า แต่ไม่มีใครพูดถึงมันฉันคิดว่ามันคุ้มค่าที่จะเพิ่ม:

หากคุณต้องการแสดงเนื้อหาแบบสแตติก (พูดถึงหน้า 'เกี่ยวกับ' รูปภาพ css ฯลฯ ) คุณสามารถใช้หนึ่งในโมดูลการให้บริการเนื้อหาแบบคงที่ตัวอย่างเช่นโหนดแบบคงที่ (มีคนอื่นที่อาจจะดีกว่าหรือแย่กว่านั้นลอง search.npmjs.org) ด้วยการประมวลผลล่วงหน้าเล็กน้อยคุณสามารถกรองหน้าแบบไดนามิกจากสแตติกและส่งไปยังตัวจัดการคำร้องขอที่ถูกต้อง


1
คำตอบไม่ได้โหลดไฟล์ js อย่างถูกต้องโดยใช้โหนดคงที่แก้ปัญหาของฉัน
อาริโซน่า

19

นี่อาจเป็นสิ่งที่ดีกว่าเนื่องจากคุณจะสตรีมไฟล์มากกว่าที่จะโหลดมันทั้งหมดลงในหน่วยความจำเช่น 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);

14

นี่คือการอัปเดตคำตอบของ Muhammed Neswine

ใน Express 4.x sendfile ถูกเลิกใช้แล้วและต้องใช้ฟังก์ชันsendFile ความแตกต่างคือ sendfile ใช้พา ธ สัมพัทธ์และ sendFile ใช้พา ธ สัมบูรณ์ ดังนั้นชื่อ __ จะถูกใช้เพื่อหลีกเลี่ยงการเข้ารหัสฮาร์ดไดรฟ์

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

12

มันเป็นวิธีที่ยืดหยุ่นและง่ายต่อการใช้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...');

10

วิธีที่ดีที่สุดที่ฉันเรียนรู้คือการใช้ express กับไฟล์ html เนื่องจาก 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");

สะอาดและดีที่สุด .. !!!


6

วิธีง่าย ๆ คือใส่ไฟล์ทั้งหมดของคุณรวมถึง index.html หรืออะไรก็ได้ที่มีทรัพยากรทั้งหมดเช่น CSS, JS ฯลฯ ในโฟลเดอร์สาธารณะหรือคุณสามารถตั้งชื่อไฟล์ตามที่คุณต้องการและตอนนี้คุณสามารถใช้ express js และบอกแอป เพื่อใช้ _dirname เป็น:

ใน server.js ของคุณโดยใช้ด่วนเพิ่มเหล่านี้

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

และถ้าคุณต้องการที่จะมีไดเรกทอรีแยกเพิ่ม dir ใหม่ภายใต้ไดเรกทอรีสาธารณะและใช้เส้นทางนั้น "/ สาธารณะ / YourDirName"

ดังนั้นเรากำลังทำอะไรที่นี่อย่างแน่นอน? เรากำลังสร้างแอปด่วนชื่ออินสแตนซ์และเรากำลังให้ที่อยู่หากไดเรกทอรีสาธารณะเข้าถึงทรัพยากรทั้งหมด หวังว่านี่จะช่วยได้!


6

วิธีการเกี่ยวกับการใช้โมดูลด่วน?

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

    app.get('/',function(request,response){
       response.sendFile(__dirname+'/XXX.html');
    });

    app.listen('8000');

จากนั้นคุณสามารถใช้เบราว์เซอร์เพื่อรับ / localhost: 8000


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

2
ผมไม่คิดว่ามันเป็นแต่ค่อนข้างresponse.writeHeader() response.writeHead()
edwin

response.writeHeader()และresponse.writeHead()ทั้งคู่ถูกต้อง
Deke

4

ฉันคิดว่านี่จะเป็นตัวเลือกที่ดีกว่าเพราะจะแสดง 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}/`);
        })
}); 

4

คุณสามารถใช้ตัวอย่างนี้:

var app = require("express");
app.get('/', function(req,res){
   res.sendFile(__dirname+'./dir/yourfile.html')
});
app.listen(3000);

4

มันง่ายมาก ๆ ถ้าคุณใช้ไพพ์ ต่อไปนี้เป็นตัวอย่างรหัส server.js

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 +- หากผู้ใช้สามารถกำหนดจุดเริ่มต้นของเส้นทางที่จะต้องตรวจสอบสิ่งเหล่านี้เช่นกัน
จอน

2

ฉันรู้ว่านี่เป็นคำถามเก่า - นี่เป็นโปรแกรมอรรถประโยชน์ไฟล์เซิร์ฟเวอร์อย่างง่ายหากคุณไม่ต้องการใช้การเชื่อมต่อหรือด่วน แต่เป็นโมดูล 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')
         }  
    })
}

2

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

1

นี่เป็นคำถามที่ค่อนข้างเก่า ... แต่ถ้ากรณีการใช้งานของคุณที่นี่คือเพียงส่งหน้า 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);

0

เราสามารถโหลดเอกสาร 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);

ฉันลอง readFile () วิธีการของ fs แต่มันล้มเหลวในการโหลดภาพนั่นคือเหตุผลที่ฉันได้ใช้กรอบการเชื่อมต่อ


0

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

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.