In todays world of the most common code to write in any programming language is to work on file handling like reading and writing to a file .
In Nodejs reading a file becomes tricky at times .In this tutorial we are going to Read files in Nodejs code with few common problems and examples that we face day to day .
There are various ways to handle file read in Nodejs , which are .
- Sychronus or Blocking
- Asynchronus or Non Blocking
- Reading all Contents At one
- Streaming File Contents.
Read a File Line By Line
The reason I consider this as a simple way is because of the complexity of the method , its pretty simple and any beginner can also start doing this .
Lets understand using code snippet how we can do this .
const fs = require('fs')
fs.readFile('/opt/ctier/names.txt', 'utf8' , (err, data) => {
if (err) {
console.error(err)
return
}
console.log(data)
})
We have used fs.readFile()
method, passing the file path as parameter, and passed a callback function that will be called with the file data to read . The data argument will have the actual contents of the file and err argument will return if any error occurred while reading the file .
Note :- Utf8 argument is necessary here , in case you do not specify the UTF* parameter this will return a Buffer Object . This was a non blocking way to read a file . Lets understand the blocking way .
var fs = require('fs');
try {
var data = fs.readFileSync('/opt/ctier/name.txt', 'utf8');
console.log(data);
} catch(e) {
console.log('Error Occurred:', e.stack);
}
This method can be used where we need to read file synchronized way . It is more of a blocking call in your code hence you need a try...
and catch..
.
Streaming files using fs.createReadStream
Now fs.createReadStream opens a readable stream to read any kind of file . If you are looking to read a file from a specific URL or looking to stream large files of 400MB we can use fs.createReadStream .
fs.createReadStream can read files from URL or from a string . We can also read files from a buffer using fs.createReadStream . Lets look at practical example of using fs.createReadStream .
const fs = require('fs');
const server = require('http').createServer();
server.on('request', (req, res) => {
const src = fs.createReadStream('/opt/movie.mp4');
src.on('error', function (error) {
console.log(error);
res.writeHead(404, 'Not Found');
res.end();
});
src.pipe(res);
});
server.listen(8000);
One of the important aspect to check in above line of code is we are using pipe to push the data in res object which is also a kind of eventEmitter . All streams in node are instances of EventEmitter hence we are able to pass that to the response .
Now there are numerous reason why should we prefer streams , here are few important ones .
- Memory Usage – Apart from normal way of reading files , reading files using streams are way beneficial in terms of memory usage . Memory usage of streams are way lower than non stream way . Have a look at memory comparison here .
- Time Efficient – It generally takes less time for sending response as streams doesn’t wait for entire file to load and send the response . It sends responses in chunks .
Related Posts