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


当前回答

使用rename函数:

fs.rename(getFileName, __dirname + '/new_folder/' + getFileName); 

在哪里

getFilename = file.extension (old path)
__dirname + '/new_folder/' + getFileName

假设您希望保持文件名不变。

其他回答

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

使用mv节点模块,它将首先尝试执行fs。重命名,然后退回到复制,然后取消链接。

根据seppo0010的注释,我使用了重命名函数来完成此操作。

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

fs。重命名(oldPath, newPath, callback) 新增于:v0.0.2 oldPath <String> | <Buffer> newPath <String> | <Buffer> . newPath <String> 回调函数> < 异步重命名(2)。除了可能的异常,没有参数 赋给完成回调函数。

如果你喜欢使用外部库,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!');

我将把所有涉及的函数(即重命名,复制,断开链接)彼此分离,以获得灵活性,并承诺一切,当然:

const renameFile = (path, newPath) => 
  new Promise((res, rej) => {
    fs.rename(path, newPath, (err, data) =>
      err
        ? rej(err)
        : res(data));
  });

const copyFile = (path, newPath, flags) =>
  new Promise((res, rej) => {
    const readStream = fs.createReadStream(path),
      writeStream = fs.createWriteStream(newPath, {flags});

    readStream.on("error", rej);
    writeStream.on("error", rej);
    writeStream.on("finish", res);
    readStream.pipe(writeStream);
  });

const unlinkFile = path => 
  new Promise((res, rej) => {
    fs.unlink(path, (err, data) =>
      err
        ? rej(err)
        : res(data));
  });

const moveFile = (path, newPath, flags) =>
  renameFile(path, newPath)
    .catch(e => {
      if (e.code !== "EXDEV")
        throw new e;

      else
        return copyFile(path, newPath, flags)
          .then(() => unlinkFile(path));
    });

moveFile只是一个方便的函数,我们可以分别应用这些函数,例如,当我们需要更细粒度的异常处理时。