Organizational Research By

Surprising Reserch Topic

how i move files on node js


how i move files on node js  using -'file,node.js,express'

How can I move files (like mv command shell) on node.js?  Is there any method for that or I need to read a file, write to new file and remove older file?
    

asked Sep 18, 2015 by dhananjayksharma
0 votes
13 views



Related Hot Questions

5 Answers

0 votes

According to seppo0010 comment, I used the rename function to do that.

http://nodejs.org/docs/latest/api/fs.html#fs_fs_rename_oldpath_newpath_callback

Thanks

answered Sep 18, 2015 by mcasudhir
0 votes

util.pump is deprecated in node 0.10 and generates warning message

 util.pump() is deprecated. Use readableStream.pipe() instead

So the solution for copying files using streams is:

var source = fs.createReadStream('/path/to/source');
var dest = fs.createWriteStream('/path/to/dest');

source.pipe(dest);
source.on('end', function() { /* copied */ });
source.on('error', function(err) { /* error */ });
answered Sep 18, 2015 by manju bhargava
0 votes

This example taken from: Node.js in Action

A move() function that renames, if possible, or falls back to copying

var fs = require('fs');

module.exports = function move (oldPath, newPath, callback) {
    fs.rename(oldPath, newPath, function (err) {
        if (err) {
            if (err.code === 'EXDEV') {
                copy();
            } else {
                callback(err);
            }
            return;
        }
        callback();
    });

    function copy () {
        var readStream = fs.createReadStream(oldPath);
        var writeStream = fs.createWriteStream(newPath);

        readStream.on('error', callback);
        writeStream.on('error', callback);
        readStream.on('close', function () {

        fs.unlink(oldPath, callback);
    });

    readStream.pipe(writeStream);

    }
}
answered Sep 18, 2015 by patelnikul321
0 votes

Here's an example using util.pump, from >> How do I move file a to a different partition in Node.js?

var fs = require('fs'),
    util = require('util');

var is = fs.createReadStream('source_file')
var os = fs.createWriteStream('destination_file');

util.pump(is, os, function() {
    fs.unlinkSync('source_file');
});
answered Sep 18, 2015 by nikhilapatil
0 votes

If you are trying to move or rename a node.js source file, try this https://github.com/viruschidai/node-mv. It will update the references to that file in all other files.

answered Sep 18, 2015 by mca.agarwal

...