Create and send html file in Nodejs

 Here we will simply create a static file using file module and then send the same file as the response.

To view the result run this file using node app.js then visit localhost:8080 in the browser

const fs = require("fs");
const http = require('http');

const str =`Hello World`;
const html =buildHTML('Hello World Page',str);
const fileName='helloWorld.html';

http.createServer(function (req, res) {
    fs.appendFile(fileName, html, function (err) {
        if (err) throw err;
        console.log('Saved!');
    })     

    fs.readFile(fileName, function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
    });

}).listen(8080);

function buildHTML(title,body){

  let html =`       
        <!doctype html>
        <html lang="en">
          <head>
            <title>${title}</title>
          <body>
            ${body}
          </body>
        </html> 
  `;

  return html;
}
Labels: ,

No comments:

Post a Comment

Popular posts from this blog

Function to create contacts in Netsuite using Suitelets

Sort an array of 0s, 1s and 2s solution in javascript

Contact Me

Name

Email *

Message *