How to transfer file a to another partition or device in Node.js?

I am trying to move a file from one section to another in a Node.js script. When I used fs.renameSync , I got Error: EXDEV, Cross-device link . I would copy it and delete the original, but I also do not see the command to copy the files. How can I do that?

+30
javascript rename
Dec 31 '10 at 7:06
source share
5 answers

You need to copy and unlink when moving files to different sections. Try it,

 var fs = require('fs'); //var util = require('util'); var is = fs.createReadStream('source_file'); var os = fs.createWriteStream('destination_file'); is.pipe(os); is.on('end',function() { fs.unlinkSync('source_file'); }); /* node.js 0.6 and earlier you can use util.pump: util.pump(is, os, function() { fs.unlinkSync('source_file'); }); */ 
+51
Dec 31 '10 at 17:18
source share

Another solution to the problem.

There's a package called fs.extra written by "coolaj86" on npm.

You use it like this: npm install fs.extra

 fs = require ('fs.extra'); fs.move ('foo.txt', 'bar.txt', function (err) { if (err) { throw err; } console.log ("Moved 'foo.txt' to 'bar.txt'"); }); 

I read the source code for this thing. It tries to execute standard fs.rename() , then if it fails, it copies and deletes the original using the same util.pump() that @chandru uses.

+7
May 26 '13 at 22:40
source share

I know this has already been answered, but I ran into a similar problem and got something like:

 require('child_process').spawn('cp', ['-r', source, destination]) 

This means that you invoke the cp ("copy") command. As we go beyond Node.js, this command should be supported by your system.

I know that this is not the most elegant, but he did what I need :)

+6
Mar 15 2018-11-11T00:
source share

to import the module and save it in the package.json file

 npm install mv --save 

then use it like this:

 var mv = require('mv'); mv('source_file', 'destination_file', function (err) { if (err) { throw err; } console.log('file moved successfully'); }); 
+4
Mar 26 '15 at 20:05
source share

I created a Node.js module that just processes it for you. You do not need to think about whether it will move in the same section or not. This is the fastest solution because it uses the recent fs.copyFile() Node.js API to copy a file when moving to another partition / disk.

Just set move-file :

 $ npm install move-file 

Then use it as follows:

 const moveFile = require('move-file'); (async () => { await moveFile(fromPath, toPath); console.log('File moved'); })(); 
+2
Nov 20 '17 at 10:18
source share



All Articles