In this shot, we'll learn to use:
statSync
method to get the size and last modified time of the file.accessSync
method to check if the file is readable.renameSync
method to rename the directory.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(".")); }
In the code above:
fs
module to interact with the file system.txt
file using the writeSync
method. This method creates a new file and adds the given content.statSync
method to get the information about the given file path synchronously. We store that information in a stats
variable.size
and mtime
property of the stats
, this denotes the size and modified time of the file.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.mkdirSync
method to create a new directory with a name temp_dir
.renameSync
method to rename the created directory to renamedDir
.RELATED TAGS
CONTRIBUTOR
View all Courses