2

Let's say I have a file "/tmp/sample.txt" and I want to move it to "/var/www/mysite/sample.txt" which is in a different volume.

How can i move the file in node.js?

I read that fs.rename only works inside the same volume and util.pump is already deprecated.

What is the proper way to do it? I read about stream.pipe, but I couldn't get it to work. A simple sample code would be very helpful.

4 Answers 4

14

Use the mv module:

var mv = require('mv');

mv('source', 'dest', function(err) {
    // handle the error
});
Sign up to request clarification or add additional context in comments.

2 Comments

is it possible to move the file from one server to another server?
my case was iterating through the songs deep inside folders and paste it in the root folder, I wrote all logic to find the songs and found this SO called awesome library mv. After the snippet has run in recursion, went to the dest folder and saw NOTHING and damn my src folder is also EMPTY, where the hell are my songs??? IMO: 1. Test it and use it. 2. Log what your doing, in my case these will help me download all songs :(
3

If on Windows and don't have 'mv' module, can we do like

var fs = require("fs"),
    source = fs.createReadStream("c:/sample.txt"),
    destination = fs.createWriteStream("d:/sample.txt");

source.pipe(destination, { end: false });
source.on("end", function(){
    fs.unlinkSync("C:/move.txt");
});

2 Comments

@nha I meant without using mv if we want to do it. I tested the code on windows so..
+1 Thank you for the precision. I tested the WriteStream functions by piping streams into it (like in stackoverflow.com/questions/11944932/… ) and it worked fine. So did the rename function. But I had problems however using symlinks (I don't usually use windows).
2

The mv module, like jbowes stated, is probably the right way to go, but you can use the child process API and use the built-in OS tools as an alternative. If you're in Linux use the "mv" command. If you're in Windows, use the "move" command.

var exec = require('child_process').exec;
exec('mv /temp/sample.txt /var/www/mysite/sample.txt', 
  function(err, stdout, stderr) {
    // stdout is a string containing the output of the command.
});

1 Comment

I'll stick with the mv module, but +1 ;)
2

You can also use spawn if exec doesn't work properly.

var spawn = require("child_process").spawn;
var child = spawn("mv", ["data.csv","./done/"]);
child.stdout.on("end", function () {                
    return next(null,"finished")
});  

Hope this helps you out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.