Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move file a to a different partition or device in Node.js?

I'm trying to move a file from one partition to another in a Node.js script. When I used fs.renameSync I received Error: EXDEV, Cross-device link. I'd copy it over and delete the original, but I don't see a command to copy files either. How can this be done?

like image 389
Jeremy Avatar asked Dec 31 '10 07:12

Jeremy


People also ask

How do I move a file in node?

js fs-extra move() Function. The move() function moves a file or a directory from source to the destination specified by the user.

How can I move a file to another directory using Javascript?

The MoveFile() method is used to move a file from a source to a destination. This method takes two parameters. The first parameter, source, is the location of the file to be moved, while the second parameter, destination, is the new location of the moved file.

How do I copy files from one directory to another in node JS?

copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, Node. js will overwrite the file if it already exists at the given destination. The optional mode parameter can be used to modify the behavior of the copy operation.


2 Answers

You need to copy and unlink when moving files across different partitions. Try this,

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'); }); */ 
like image 138
Chandra Sekar Avatar answered Sep 29 '22 04:09

Chandra Sekar


I know this is already answered, but I ran across a similar problem and ended up with something along the lines of:

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

What this does is call the command cp ("copy"). Since we're stepping outside of Node.js, this command needs to be supported by your system.

I know it's not the most elegant, but it did what I needed :)

like image 37
Justin Avatar answered Sep 29 '22 03:09

Justin