In this lesson, you will learn how to extract and interpret the hidden metadata—like birth time, modification stamps, and file size—that the operating system maintains for every file.
Understanding File Stats
Every time you create or modify a file, the operating system records metadata in an object called an fs.Stats instance. While file contents are the "data," these stats are the "data about the data." Using Node.js, we can retrieve this information to make informed decisions, such as deciding whether to process a file based on when it was last updated.
Retrieving and Interpreting Metadata
To access this information, we use the fs.stat method (or its asynchronous variant). This function communicates with the file system to return a snapshot of the file's current state.
const fs = require('fs/promises');
async function getFileInfo(filePath) {
try {
const stats = await fs.stat(filePath);
console.log(`File size: ${stats.size} bytes`);
console.log(`Created: ${stats.birthtime}`);
console.log(`Last modified: ${stats.mtime}`);
// Check if it's a regular file or a directory
console.log(`Is file? ${stats.isFile()}`);
} catch (err) {
console.error("Error reading file stats:", err.message);
}
}
Deciphering the Timestamps
When working with these objects, you will encounter three specific timestamps:
birthtime(btime): The exact moment the file was created. Note that on some file systems, this might be unavailable or reflect the last change to the file status.mtime(Modification time): The last time the content of the file was changed. This is the most common metric for cache invalidation or determining if a file is "stale."atime(Access time): The last time the file was read.
By comparing the mtime of two files, your application can intelligently skip unnecessary operations, such as re-uploading a file that hasn't been altered since the last sync. Always remember that these operations are asynchronous and rely on the underlying OS reporting, so handle potential errors—such as a file disappearing between the time you check its stats and the time you try to read it—with robust error handling.
Key Takeaway: The fs.stat object provides a standardized interface to retrieve crucial metadata like size and timestamps, allowing your application to perform logic based on the file's lifecycle rather than just its content.