Open In App

How to get information about a file using Node.js ?

Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isn’t a framework, and it’s not a programming language. In this article, we will discuss how to get information about a file using Node.js

We will use the fs module of Node.js to extract information about files. The fs module is an inbuilt module. We will use the fs.stat() module of the fs module to get all the information related to the file. If to get information about the uploaded files then we can handle them using npm packages like multer which handles all different types of files. Let us go through step by step. First, create a file in the current working directory whose information you want to view.



Step 1: Create an “app.js” file and initialize your project with npm.

npm init

Step 2: Create an info.txt file in the project folder.



 

Project structure:

Project/File Structure




//Importing fs module 
const fs = require("fs");
  
//stat methods takes path and a callback function as input
fs.stat("./info.txt", function(err, stats){
  
    //Checking for errors
   if(err){
       console.log(err)
   }
   else{
    //Logging the stats Object
   console.log(stats)
   }
});

Run app.js file using below command:

node app.js

Now before looking over the output let us discuss the attributes of the Stats Object:

Output:

Output

So by using the file system of nodeJS you can get all the required information about any file in the local file system.

Article Tags :