Node.Js is a great framework to build I/O applications where there are too many database interactions. Sometimes we need to read bytes of files using Node.Js. In this post, we will cover how to read last n bytes of file using node.js.
Table of Contents
Step 1
Create a file named app.js
and require fs
module in the file.
1 | var fs = require('fs'); |
Step 2
Use fs.stat
to get the file size.
1 2 3 4 5 6 | fs.stat('test.txt', function(err, stats) { // file size info goes here var fileSize = stats.size; var bytesToRead = 10; /* <--- Here is the number N. It will read the last 10 bytes of the file */ var position = fileSize - bytesToRead; /* <--- Specify the position from where you want to read the file */ }); |
Step 3
Open and read the file using fs.open
and fs.read
with file size, position etc values.
1 2 3 4 5 | fs.open('test.txt', 'r', function(errOpen, fd) { fs.read(fd, Buffer.alloc(bytesToRead), 0, bytesToRead, pos, function(errRead, bytesRead, buffer) { console.log(buffer.toString('utf8')); }); }); |
Step 4
The complete code goes here-
1 2 3 4 5 6 7 8 9 10 11 12 | var fs=require('fs'); fs.stat('test.txt', function(err, stats) { const fileSize = stats.size; const bytesToRead = 10; const position = fileSize - bytesToRead; fs.open('test.txt', 'r', function(errOpen, fd) { fs.read(fd, Buffer.alloc(bytesToRead), 0, bytesToRead, position, function(errRead, bytesRead, buffer) { console.log(buffer.toString('utf8')); }); }); }); |
Here are the contents of my test file-
Result after reading last 10 bytes-
Share your issues/concerns if you get any while reading the bytes of file.
Thanks
1 thought on “How to read last N bytes of file using NodeJs”