user3121600
user3121600

Reputation: 131

Need help in fetching all files in directory based on file extension using Javascript

I have folder having multiple '.txt' files along with one 'backup' folder. Now I want to fetch all files based on its '.txt' extension and wanted to move them in 'backup' folder. I am using Node.js.

Please let me know if anyone has any suggestions.

Regards,

Manan

Upvotes: 0

Views: 324

Answers (2)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

Sync solution, something like:

var dirPath = 'myDir/';
fs.readdirSync(dirPath).forEach(function(file){
   if(/\.txt$/.test(file)){  //If it's a txt file
       fs.renameSync(dirPath  + file, + 'backup/' + file)
   }
});

Cheers, from La Paz, Bolivia

Upvotes: 1

Basel
Basel

Reputation: 71

Use fs.rename function http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback

fs.rename(oldPath, newPath, function(){
   console.log(oldPath + ' Moved to: ' + newPath);
});

Upvotes: 0

Related Questions