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.
Step 1
Create a file named app.js
and require fs
module in the file.
var fs = require('fs');
Step 2
Use fs.stat
to get the file size.
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.
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-
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