3

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.

3
  • Sure, but you have to do all of the work yourself. If you want to write a server, why not just use Express? Commented Jul 29, 2020 at 20:31
  • I want to practice it in Node.js. It is only two lines of code http.createServer() and server.on('request') that part about creating server is not complicated. Commented Jul 29, 2020 at 20:33
  • nodejs.org/dist/latest-v12.x/docs/api/… Commented Jul 29, 2020 at 20:36

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I found similar solution, I wrote it up in question. I was wondering is it possible to write html directly in method without getting it from another file. (I was looking for something similar to JSX in React to return data in that manner) But this is also helpful.
Your first answer is what I was looking for. I didn't know that I need to add this res.writeHead(200, { 'Content-Type':'text/html'}); and I was trying without it. Thanks man!
I'm glad I could help :)
In res.writeHead(200, { 'Content-Type':'text/html'}); you notify what type of response you will send. And that is reason why method res.end() or res.write() accept html type as response. Is that correct?
Yeah, that's pretty much it
2

First, you need to mention the content type as HTML. Then read the HTML file using fs module and send its data as a response. Don't forget to end the response using end() method.

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

const server = http.createServer((req, res) => {
  res.setHeader("Content-Type", "text/html");
  fs.readFile('./views/index.html', (err, data) => {
    if(err) {
      console.log(err);
      res.end();
    } else {
      res.write(data);
      res.end();
    }
  })
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.