How to work with files in Node.js

Overview

In this shot, we'll learn to use:

  • The statSync method to get the size and last modified time of the file.

  • The accessSync method to check if the file is readable.

  • The renameSync method to rename the directory.

Code example

The code below demonstrates how to implement the operations above:

const fs = require('fs');
// create a new file
let fileName = "newfile.txt";
fs.writeFileSync(fileName,"sample content");
const stats = fs.statSync(fileName);
console.log("The size of the file is : " + stats.size + " bytes");
console.log(`The Last Modified time is. : ${stats.mtime}`);
// check if the file is readable and writable
try{
fs.accessSync(fileName, fs.constants.R_OK | fs.constants.W_OK)
console.log("The file is readable and writable ");
} catch(e) {
console.log(e);
}
let dirname = "temp_dir";
fs.mkdirSync(dirname);
printFilesInCurrentDir();
// rename directory
fs.renameSync(dirname, "renamedDir");
console.log("\nAfter renaming directory.")
printFilesInCurrentDir();
function printFilesInCurrentDir(){
console.log("\nFile in current directory")
console.log(fs.readdirSync("."));
}

Code explanation

In the code above:

  • Line 1: We import the fs module to interact with the file system.

  • Line 5: We create a new txt file using the writeSync method. This method creates a new file and adds the given content.

  • Line 7: We use the statSync method to get the information about the given file path synchronously. We store that information in a stats variable.

  • Lines 8 and 9: We access the size and mtime property of the stats, this denotes the size and modified time of the file.

  • Line 13: We use the accessSync method to synchronously check the file permission. We check permission to read and write using the fs.constants.R_OK and | fs.constants.W_OK constants. And we can use the fs.constants.F_OK constant to check if the file exists.

  • Line 20: We use the mkdirSync method to create a new directory with a name temp_dir.

  • Line 24: We use the renameSync method to rename the created directory to renamedDir.

Free Resources