Loading basic HTML in Node.js

后端 未结 20 1280
暗喜
暗喜 2020-11-28 17:34

I\'m trying to find out how to load and render a basic HTML file so I don\'t have to write code like:

response.write(\'...

blahblahblah

...\
相关标签:
20条回答
  • 2020-11-28 18:09

    I just found one way using the fs library. I'm not certain if it's the cleanest though.

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

    The basic concept is just raw file reading and dumping the contents. Still open to cleaner options, though!

    0 讨论(0)
  • 2020-11-28 18:12

    This is an update to Muhammed Neswine's answer

    In Express 4.x, sendfile has been deprecated and sendFile function has to be used. The difference is sendfile takes relative path and sendFile takes absolute path. So, __dirname is used to avoid hardcoding the path.

    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'));
    });
    
    0 讨论(0)
  • 2020-11-28 18:14

    Adding another option - based on the excepted answer.

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

    (*) Example above is using with nestjs and node-html-parser.

    0 讨论(0)
  • 2020-11-28 18:15

    How about using express module?

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

    then, you can use browser to get /localhost:8000

    0 讨论(0)
  • 2020-11-28 18:18

    use ejs instead of 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' });};
    
    0 讨论(0)
  • 2020-11-28 18:19

    The easy way to do is, put all your files including index.html or something with all resources such as CSS, JS etc. in a folder public or you can name it whatever you want and now you can use express js and just tell app to use the _dirname as :

    In your server.js using express add these

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

    and if you want to have seprate directory add new dir under public directory and use that path "/public/YourDirName"

    SO what we are doing here exactly? we are creating express instance named app and we are giving the adress if the public directory to access all the resources. Hope this helps !

    0 讨论(0)
提交回复
热议问题