【问题标题】:Loading basic HTML in Node.js在 Node.js 中加载基本 HTML
【发布时间】:2011-06-10 20:35:57
【问题描述】:

我正在尝试了解如何加载和呈现基本 HTML 文件,因此我不必编写如下代码:

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

【问题讨论】:

    标签: html node.js


    【解决方案1】:

    我刚刚发现一种方法是使用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);
    });
    

    基本概念只是原始文件读取和转储内容。不过,仍然有更清洁的选择!

    【讨论】:

    • 您应该在您的情况下使用 fs.readFileSync,如果页面显示为未定义会很糟糕。但是,是的,这是制作基本 html 服务器的好方法
    • sys = require('util') 不需要,因为控制台不会打印任何内容。
    • 这会将整个文件读入内存,并在每个请求中。你真的应该从磁盘流式传输文件而不是缓冲它。此类事物存在高质量的库,例如 senchalabs.org/connectgithub.com/cloudhead/node-static
    • 我认为应该是 writeHead(...) 而不是 writeHeader(...)...Node.js response.writeHead()
    • @generalhenry 更好的是,对fs.readFile 的调用可以放在对http.createServer 的调用中,从而可以处理错误。将 Stephen 的答案与 if (err) { console.log('something bad'); return res.end('Oops! Something bad happened.');} 一起使用 return 语句是新用户可能会忽略的简单事情。
    【解决方案2】:

    使用 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
    • 表示弃用 res.sendfile:改用 res.sendFile stackoverflow.com/a/26079640/3166417
    • 好答案。对于那些不知道如何在 app.get.... 之前使用 express 类型的人:var express = require('express'); var app = express();
    • npm install express --save代替-g
    • 不需要添加 app.listen(port || 3000, ()=>{console.log("server is up")} ) 吗?
    【解决方案3】:

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

    【讨论】:

    • 是的,这与我想出的大致相同。也感谢 Express 的建议。它非常可爱,我很确定我会在下一个项目中使用它。我的目标是在让框架为我完成繁重工作之前弄清楚它是如何在幕后完成的。
    • 杀毒防火墙可以禁用此招
    【解决方案4】:

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

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

    【讨论】:

    • 答案没有正确加载js文件,使用node-static解决了我的问题。
    【解决方案5】:

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

    【讨论】:

      【解决方案6】:

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

      【讨论】:

        【解决方案7】:

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

        【讨论】:

          【解决方案8】:

          我学到的最好方法是使用带有 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");
          

          干净和最好的..!!!

          【讨论】:

            【解决方案9】:

            如果你使用管道,这真的很简单。以下是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 +,像~ 这样的目录路径字符就可以了 - 如果用户可以确定路径的开始,则还需要检查这些字符。
            【解决方案10】:

            最简单的方法是,将所有文件,包括 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 的快速实例,如果公共目录访问所有资源,我们将提供地址。 希望这可以帮助 !

            【讨论】:

              【解决方案11】:
                 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() 都有效。
              【解决方案12】:

              使用 express 模块怎么样?

                  var app = require('express')();
              
                  app.get('/',function(request,response){
                     response.sendFile(__dirname+'/XXX.html');
                  });
              
                  app.listen('8000');
              

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

              【讨论】:

                【解决方案13】:

                我认为这是一个更好的选择,因为它显示了运行服务器的 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}/`);
                        })
                }); 
                

                【讨论】:

                  【解决方案14】:

                  你也可以使用这个 sn-p:

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

                  【讨论】:

                    【解决方案15】:

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

                    【讨论】:

                      【解决方案16】:

                      这是一个很老的问题...但是如果您的用例只是临时将特定的 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);
                      

                      【讨论】:

                        【解决方案17】:

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

                        【讨论】:

                          【解决方案18】:

                          我们可以使用连接框架加载 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框架。

                          【讨论】:

                            【解决方案19】:

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

                            【讨论】:

                              【解决方案20】:

                              添加另一个选项 - 基于例外答案。

                              对于打字稿

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

                              (*) 上面的示例与nestjsnode-html-parser 一起使用。

                              【讨论】:

                                【解决方案21】:

                                可以直接在end方法中加载HTML

                                response.end('...<p>blahblahblah</p>...')
                                

                                一样
                                response.write('...<p>blahblahblah</p>...')
                                response.end()
                                

                                【讨论】:

                                  【解决方案22】:

                                  试试这个:

                                  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。如果需要,您可以添加更多内容。

                                  【讨论】:

                                    【解决方案23】:
                                    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 文件的名称

                                    【讨论】:

                                      猜你喜欢
                                      • 1970-01-01
                                      • 2014-09-26
                                      • 2017-12-05
                                      • 2017-02-14
                                      • 1970-01-01
                                      • 2014-03-17
                                      • 2011-05-31
                                      • 2013-04-10
                                      • 1970-01-01
                                      相关资源
                                      最近更新 更多