如何在node.js上移动文件(如mv命令shell) ?是否有任何方法,或者我应该读取一个文件,写到一个新文件,并删除旧文件?


当前回答

这个例子摘自:Node.js in Action

move()函数,如果可能,将重命名或返回到复制

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);
    }
}

其他回答

跑龙套。节点0.10弃用Pump,产生警告信息

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

因此,使用流复制文件的解决方案是:

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 */ });

对于8.0.0以上的Node版本使用承诺:

const {promisify} = require('util');
const fs = require('fs');
const {join} = require('path');
const mv = promisify(fs.rename);

const moveThem = async () => {
  // Move file ./bar/foo.js to ./baz/qux.js
  const original = join(__dirname, 'bar/foo.js');
  const target = join(__dirname, 'baz/qux.js'); 
  await mv(original, target);
}

moveThem();

这是对teoman shipahi的回答的重新讨论,使用了一个稍微不那么模糊的名称,并遵循了在尝试调用代码之前定义代码的设计原则。(虽然node允许您做其他事情,但本末倒置并不是一个好的实践。)

function rename_or_copy_and_delete (oldPath, newPath, callback) {

    function copy_and_delete () {
        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);
    }

    fs.rename(oldPath, newPath, 
        function (err) {
          if (err) {
              if (err.code === 'EXDEV') {
                  copy_and_delete();
              } else {
                  callback(err);
              }
              return;// << both cases (err/copy_and_delete)
          }
          callback();
        }
    );
}

在下面URL的帮助下,您可以复制或移动您的文件CURRENT Source到Destination Source

https://coursesweb.net/nodejs/move-copy-file

/*********Moves the $file to $dir2 Start *********/ var moveFile = (file, dir2)=>{ //include the fs, path modules var fs = require('fs'); var path = require('path'); //gets file name and adds it to dir2 var f = path.basename(file); var dest = path.resolve(dir2, f); fs.rename(file, dest, (err)=>{ if(err) throw err; else console.log('Successfully moved'); }); }; //move file1.htm from 'test/' to 'test/dir_1/' moveFile('./test/file1.htm', './test/dir_1/'); /*********Moves the $file to $dir2 END *********/ /*********copy the $file to $dir2 Start *********/ var copyFile = (file, dir2)=>{ //include the fs, path modules var fs = require('fs'); var path = require('path'); //gets file name and adds it to dir2 var f = path.basename(file); var source = fs.createReadStream(file); var dest = fs.createWriteStream(path.resolve(dir2, f)); source.pipe(dest); source.on('end', function() { console.log('Succesfully copied'); }); source.on('error', function(err) { console.log(err); }); }; //example, copy file1.htm from 'test/dir_1/' to 'test/' copyFile('./test/dir_1/file1.htm', './test/'); /*********copy the $file to $dir2 END *********/

fs-extra模块允许你用它的move()方法来做这件事。我已经实现了它,它工作得很好,如果你想完全移动一个文件从一个目录到另一个-即。从源目录中删除文件。应该适用于大多数基本情况。

var fs = require('fs-extra')

fs.move('/tmp/somefile', '/tmp/does/not/exist/yet/somefile', function (err) {
 if (err) return console.error(err)
 console.log("success!")
})