How to work with files in Node.js
Overview
In this shot, we'll learn to use:
The
statSyncmethod to get the size and last modified time of the file.The
accessSyncmethod to check if the file is readable.The
renameSyncmethod to rename the directory.
Code example
The code below demonstrates how to implement the operations above:
const fs = require('fs');// create a new filelet 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 writabletry{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 directoryfs.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
fsmodule to interact with the file system.Line 5: We create a new
txtfile using thewriteSyncmethod. This method creates a new file and adds the given content.Line 7: We use the
statSyncmethod to get the information about the given file path synchronously. We store that information in astatsvariable.Lines 8 and 9: We access the
sizeandmtimeproperty of thestats, this denotes the size and modified time of the file.Line 13: We use the
accessSyncmethod to synchronously check the file permission. We check permission to read and write using thefs.constants.R_OKand| fs.constants.W_OKconstants. And we can use thefs.constants.F_OKconstant to check if the file exists.Line 20: We use the
mkdirSyncmethod to create a new directory with a nametemp_dir.Line 24: We use the
renameSyncmethod to rename the created directory torenamedDir.