Nodejs, do more with the 'fs' Module
Node.js provides the fs module, which allows you to interact with the file system. The module allows you to create, read , and modify files. However, the module can do a lot more than just read and write files, for example you can do the following :Â
Verify Path Exist
fs.exists(path, callback)
fs.existsSync(path)
     Both function return true or false
fs.exists('grano-StreamWrites.txt', function(res) { console.log(res ? "Path is there" : "Path is not there"); });
Get File InformationÂ
fs.stat(path, callback)
fs.statSync(path)
Both function return a Stats object (http://nodejs.org/api/fs.html#fs_class_fs_stats)
fs.stat('grano-StreamWrites.txt',function(err, res) { if(!err){ console.log('stats : ' + JSON.stringify(res, null, ' ')); res.isDirectory(); res.isBlockDevice(); res.isFIFO(); } });
List Files in Directory
fs.readdir(path, callback)
fs.readdirSync(path, callback)
var path = require('path'); function viewDir (dirPath) { console.log (' Directory Path = > ' + dirPath); fs.readdir(dirPath,function(err , res) { for (var idx in res){ var fullPath = path.join(dirPath, res[idx]); (function(fullPath) { fs.stat(fullPath,function(err, stats) { if (stats && stats.isFile()) { console.log(fullPath); } else if (stats && stats.isDirectory()){ viewDir(fullPath); } }); })(fullPath); } }); } viewDir("/Users/username/Documents/");
Delete Files
fs.unlink(path, callback)
fs.unlinkSync(path)
     Both function return true or false
fs.unlink("filename.txt", function(err) { console.log( err ? "File Deleted Failed" : "File Deleted "); });
Truncating Files
   This option is very useful for temp logs files
fs.truncate(path, len, callback)
fs.truncateSync(path, len)
     Both function return true or false
fs.truncate('file.txt', function(err) { console.log(err ? "File Was not Truncated" : "File was truncated"); });
Create FoldersÂ
fs.mkdir(path , callback)Â
fs.mkdirSync(path)
fs.mkdir("./Folder1", function(err) { if(!err){ fs.mkdir("./Folder1/Folder2",function(err) { if (!err) {console.log("Folder Created")}; }); } });
   Note: remember that the fs.mkdir is an asynchronous method so we need to wait for the call back in order to create a subfolder
Delete FolderÂ
fs.rmdir(path, callback)
fs.rmdirSync(path)
fs.rmdir("./Folder1/Folder2", function(err) { if(!err){ fs.rmdir("./Folder1",function(err) { if (!err) {console.log("Folder Deleted Created")}; }); } });
Renaming Files and DirÂ
fs.rename (old_path,new_path, callback)
fs.renameSync (old_path, new_path)
fs.rename("File1.pdf","FileNewName.pdf",function(err) { console.log(err ? "Error Fail to rename file " : "File Renamed"); }); fs.rename("./Dirname","./NewDirname",function(err) { console.log(err ? "Error Fail to rename Dir " : "Dir Renamed"); });







