Loading basic HTML in Node.js

后端 未结 20 1385
暗喜
暗喜 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: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.

提交回复
热议问题