a blog for those who code

Friday, 6 March 2015

Move file within directory in NodeJS

In this post we will show you how to move files within the directory in NodeJS. Sometimes you need to move the files when you are building your application in NodeJS that accesses the file system.

Before going into the code we will understand the rename method in Nodejs.

fs.rename(oldPath, newPath, callback) - In this we will rename the old path of the file with the new one. If either the old or new argument names a symbolic link, rename() shall operate on the symbolic link itself, and shall not resolve the last component of the argument.

Code :

var fs = require('fs'),
origPath,
newPath,
args = process.argv;

if(args.length !== 4) {

throw new Error('Invalid Arguments');
} else {
oldPath = args[2];
newPath = args[3];
}
fs.rename(oldPath, newPath, function(error){
if(error)
throw error;
});

Example : 


In the above example we are moving a example8.js file from subFolder to newFolder.

How to move file to a different partition or device

var fs = require('fs');

var source = fs.createReadStream('source_file_path');

var desti = fs.createWriteStream('destination_file_path');

source.pipe(desti);

source.on('end',function() {
    fs.unlink('source_file_path', function(err) {
if(err) throw err;
});
});

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License