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


当前回答

本地使用nodejs

var fs = require('fs')

var oldPath = 'old/path/file.txt'
var newPath = 'new/path/file.txt'

fs.rename(oldPath, newPath, function (err) {
  if (err) throw err
  console.log('Successfully renamed - AKA moved!')
})

(注意:“如果您正在跨分区或使用不支持移动文件的虚拟文件系统,这将不起作用。[…——Flavien Volken 15年9月2日12:50)

其他回答

本地使用nodejs

var fs = require('fs')

var oldPath = 'old/path/file.txt'
var newPath = 'new/path/file.txt'

fs.rename(oldPath, newPath, function (err) {
  if (err) throw err
  console.log('Successfully renamed - AKA moved!')
})

(注意:“如果您正在跨分区或使用不支持移动文件的虚拟文件系统,这将不起作用。[…——Flavien Volken 15年9月2日12:50)

这个例子摘自: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);
    }
}

如果您试图移动或重命名一个node.js源文件,请尝试https://github.com/viruschidai/node-mv。它将更新所有其他文件中对该文件的引用。

fs。Rename在同步版本中也可用:

fs.renameSync(oldPath, newPath)

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