Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js send HTML as response to client

Tags:

node.js

Is it possible in Node.js to return HTML (e.g. <div>Test</div>) as response to client?

I saw that option in Express on sendFile() method().

Is there something similar in Node?

I found this solution:

var myHtmlData;
fs.readFile('./index.html', (err, data) => {
    if(err){
        throw err;
    } else {
        myHtmlData = data
    }
  })
  // and after use it 
 response.write(myHtmlData)

But I was wondering is it possible to do it with some method similar to sendFile() to write html directly like this <div>Test</div> without reading it from another file.

like image 625
Predrag Davidovic Avatar asked Mar 27 '26 09:03

Predrag Davidovic


1 Answers

Sure. It's pretty simple. The following code returns the response as HTML to the client.

var http = require('http');

http.createServer(function(req, res){
   if(req.url === "/"){
      res.writeHead(200, { 'Content-Type':'text/html'});
      res.end("<div><p>Test<p></div>");
   }
}).listen(3000);

And in case you want to serve an HTML or JSON file as a response, you can execute the following code.

var http = require('http');
var fs = require('fs');

http.createServer(function(req, res){

    if(req.url === '/I_want_json'){

        res.writeHead(200, { 'Content-Type':'application/json'});

        var obj = {
            firstName: "Jane",
            lastName: "Doe",
        };

        res.end(JSON.stringify(obj));
    }
    else if (req.url === '/I_want_html'){
        res.writeHead(200, { 'Content-Type':'text/html'});
        html = fs.readFileSync('./index.html');
        res.end(html);
    }
    else{
        res.writeHead(404);
        res.end();
    }
}).listen(3000, '127.0.0.1');

Do not forget to set the Content-Type as mentioned since it is a mandatory part for client to distinguish the type of response.

like image 128
Ashkan R. Nejad Avatar answered Mar 30 '26 01:03

Ashkan R. Nejad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!