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


当前回答

如果你喜欢使用外部库,Shelljs是一个非常方便的解决方案。

命令: Mv ([options,] source, destination)

可用的选项:

-f: force(默认行为)

-n:防止覆盖

const shell = require('shelljs');
const status = shell.mv('README.md', '/home/my-dir');
if(status.stderr)  console.log(status.stderr);
else console.log('File moved!');

其他回答

下面是一个使用util的例子。我如何移动文件a到不同的分区或设备在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');
});

跑龙套。节点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 */ });

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!")
})

就像上面的回答中所说的那样,我的2分:copy()方法不应该在没有轻微调整的情况下原样用于复制文件:

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

    readStream.on('error', callback);
    writeStream.on('error', callback);

    // Do not callback() upon "close" event on the readStream
    // readStream.on('close', function () {
    // Do instead upon "close" on the writeStream
    writeStream.on('close', function () {
        callback();
    });

    readStream.pipe(writeStream);
}

复制函数封装在Promise中:

function copy(oldPath, newPath) {
  return new Promise((resolve, reject) => {
    const readStream = fs.createReadStream(oldPath);
    const writeStream = fs.createWriteStream(newPath);

    readStream.on('error', err => reject(err));
    writeStream.on('error', err => reject(err));

    writeStream.on('close', function() {
      resolve();
    });

    readStream.pipe(writeStream);
  })

但是,请记住,如果目标文件夹不存在,文件系统可能会崩溃。

这是对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();
        }
    );
}