在Node.js中加载基本HTML

在Node.js中加载基本HTML,html,node.js,Html,Node.js,我试图找出如何加载和呈现基本HTML文件,这样我就不必编写如下代码: response.write('...<p>blahblahblah</p>...'); response.write(“…blahblahblah”); 我刚刚找到了一种使用。但我不确定这是不是最干净的 var http = require('http'), fs = require('fs'); fs.readFile('./index.html', function (err, ht

我试图找出如何加载和呈现基本HTML文件,这样我就不必编写如下代码:

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

”);
我刚刚找到了一种使用。但我不确定这是不是最干净的

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对象手动回显文件,但我建议您使用该框架以使您的生活更加轻松

…但如果你坚持用艰难的方式来做:

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

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

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

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

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

app.get('/', function(request, response){
    response.sendFile('absolutePathToYour/htmlPage.html');
});
就这么简单。 为此,请使用express模块。 Install express:
npm Install express-g

这是对的更新

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

使用ejs代替翡翠

npm安装ejs

app.js

./routes/index.js


我学到的最好的方法是将express与html文件一起使用,因为express有很多优点。如果你想的话,你也可以把它扩展到Heroku平台上……只需说:)


干净和最好的

最简单的方法是,将所有文件(包括index.html或包含CSS、JS等所有资源的文件)放在公用文件夹中,或者您可以随意命名,现在您可以使用express JS,只需告诉应用程序使用_dirname即可:

使用express在server.js中添加以下内容

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
如果您想让seprate目录在public目录下添加新目录,并使用路径“/public/YourDirName”

那么我们到底在这里做什么? 我们正在创建一个名为app的express实例,并为访问所有资源的公共目录提供地址。
希望这有帮助

使用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}/`);
        })
}); 
var http=require('http'),
fs=要求('fs');
常量主机名=“”;
常数端口=3000;
const html=fs.readFile('./index.html',函数(err,html){
如果(错误){
犯错误;
}
http.createServer(函数(请求、响应){
writeHeader(200,{“内容类型”:“text/html”});
response.write(html);
response.end();
}).侦听(端口、主机名,()=>{
log(`Server running at http://${hostname}:${port}/`);
})
}); 

以下是我使用Express server托管静态HTML文件的简单演示代码

希望对你有帮助

//用于HTML页面的simple express服务器!
//ES6风格
const express=require('express');
常数fs=要求('fs');
常量主机名='127.0.0.1';
常数端口=3000;
常量app=express();
让缓存=[];//阵列正常!
cache[0]=fs.readFileSync(uu dirname+'/index.html');
cache[1]=fs.readFileSync(uu dirname+'/views/testview.html');
应用程序获取(“/”,(请求,请求)=>{
res.setHeader('Content-Type','text/html');
res.send(缓存[0]);
});
app.get('/test',(req,res)=>{
res.setHeader('Content-Type','text/html');
res.send(缓存[1]);
});
应用程序侦听(端口,()=>{
console.log(`
服务器正在http://${hostname}:${port}/
服务器主机名${hostname}正在侦听端口${port}!
`);

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

您还可以使用以下代码段:

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

如果你用管道的话就很简单了。下面是server.js代码片段

var http=require('http');
var fs=需要('fs');
功能onRequest(req、res){
log(“用户提出请求。”+req.url);
res.writeHead(200,{'Content-Type':'text/html'});
var readStream=fs.createReadStream(uu dirname+'/index.html','utf8');
/*包括您的html文件和目录名,而不是*/
readStream.pipe(res);
}
http.createServer(onRequest).listen(7000);

log('Web服务器正在运行…')添加另一个选项-基于例外答案

对于Typescript

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();
  }
}
(*)上面的示例与and一起使用。

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

response.end(“…blahblahblah

”)
这和

response.write(“…blahblahblah

”) 答复: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源代码时包含它们,并且可以加载图标、IMG、GIF。如果你想,你可以添加更多,如果你需要

   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 ");
var app = require("express");
app.get('/', function(req,res){
   res.sendFile(__dirname+'./dir/yourfile.html')
});
app.listen(3000);
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();
  }
}
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);