0
0
Node.jsframework~15 mins

Checking file existence and stats in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Checking file existence and stats
📖 Scenario: You are building a small Node.js script to check if a file exists and get its details like size and creation date. This is useful when you want to verify files before processing them.
🎯 Goal: Create a Node.js script that checks if a file named example.txt exists in the current folder. If it exists, get its size and creation time using Node.js fs module.
📋 What You'll Learn
Use Node.js fs module
Check if example.txt exists
Get file stats if it exists
Extract file size and creation time from stats
💡 Why This Matters
🌍 Real World
Checking if files exist and reading their details is common in scripts that process files, like backup tools or media managers.
💼 Career
Understanding file system operations with Node.js is important for backend developers and automation engineers.
Progress0 / 4 steps
1
Import the fs module and define the file path
Write a line to import the Node.js fs module using import fs from 'fs'. Then create a constant called filePath and set it to the string './example.txt'.
Node.js
Need a hint?

Use ES module syntax to import fs. Define filePath exactly as './example.txt'.

2
Create a variable to check if the file exists
Write a line to create a constant called fileExists that uses fs.existsSync(filePath) to check if the file exists.
Node.js
Need a hint?

Use fs.existsSync with filePath to check existence.

3
Get file stats if the file exists
Write an if statement that checks if fileExists is true. Inside the block, create a constant called stats and set it to fs.statSync(filePath) to get the file stats.
Node.js
Need a hint?

Use if (fileExists) and inside it call fs.statSync(filePath).

4
Extract and store file size and creation time
Inside the if block, create two constants: fileSize set to stats.size and creationTime set to stats.birthtime.
Node.js
Need a hint?

Use stats.size and stats.birthtime to get size and creation time.