Friday 19 October 2018

Node.js: http: Serve files

In this post, I am going to explain how to serve the file content.

Let’s say ‘data.txt’ contains below content.

data.txt
Hello, How are you
I am fine, thank you....
This is the end of the file

Step 1: Get a readable stream for data.txt file.
    var readableStream = fs.createReadStream(filePath, {
        encoding: 'utf-8'
    });

Step 2: Use pipe method of readable stream to write the data to response writeable stream.
readableStream.pipe(response);

Find the below working application.

HelloWorld.js
var http = require('http');
var fs = require('fs');

var filePath = 'data.txt';

var server = http.createServer((request, response) => {
    response.writeHead(200, {
        'Content-Type': 'text/plain'
    });

    var readableStream = fs.createReadStream(filePath, {
        encoding: 'utf-8'
    });

    readableStream.pipe(response);
});

server.listen(9000);

console.log('Server started and listening on port 9000');


Open browser and hit the url ‘http://localhost:9000/’, you can see below kind of screen.




Previous                                                 Next                                                 Home

No comments:

Post a Comment