This step-by-step guide will show you how to get or obtain file size in the Node js application. From scratch, you will understand how to set up a node js application and write the functions to get the file size in kb and megabytes (MB).
To check the image file size in node, we will use the fs.statSync(). The statSync() method synchronously return the data regarding the given file path.
The statSync method takes two parameters, path, and options. Conversely, it returns a state object that holds the information about the file path. Let us find out how to get the file size in MB in node js.
Node JS Get File / Image Size Example
- Step 1: Create Project Folder
- Step 2: Build Node App
- Step 3: Create Node Index File
- Step 4: Start Application
Create Project Folder
The proliferation of small functionality starts with setting up a Node project.
The very first thing that you have to do is to move on to the terminal.
You may choose, terminal app or integrated terminal in your favourite code editor.
Afterwards, you have to use the traditional mkdir command followed by your project name.
Subsequently, you have to press enter to order the terminal to create the project directory.
Build Node App
The starting of building a node application starts with node package initializer command.
Here is the command that you need to invoke from the terminal.
After you ran the command, some questions appear on your screen like – name, version, description, author, and license.
Thereafter, given above command, generates a package.json file.
The package.json file is the backbone of any Node project. It registers the essential metadata about a node project.
It holds functional properties of a project, such as entry point to our package and scripts execution.
Create Node Index File
Also, in you node project, create and `img` folder and here in this directory, you have to temporarily keep the image file.
Now, you have to create the index.js file at the root of your node app folder. Make sure to append the given code in the file.
const fs = require('fs'); const fileUrl = './img/star-trek.jpeg'; let fileDetail = fs.statSync(fileUrl); let imageSize = fileDetail.size; let imageSizeMB = fileDetail.size / (1024*1024); console.log('Size File in MB:' + imageSizeMB); console.log('Image Size:' + imageSize);
We have written the code, and we are ready to print the result on the terminal screen.
Head over to the command prompt, write the given command, hit enter to evoke the output.
Finally, based on the image we used, we got the file sizes:
#: Size File in MB:0.18434715270996094 #: Image Size:193302
Node is a light, scalable, open-source language platform that makes the app-building process incredibly effortless. It serves all types of purposes. Be it smaller apps or enterprise level.
In this tutorial, we learned to set up a node app from scratch and saw how to grab the image file size using the statSync() method.
I hope this quick guide will help you in node development.