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


当前回答

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

fs.renameSync(oldPath, newPath)

其他回答

下面是一个使用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');
});

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

根据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)。除了可能的异常,没有参数 赋给完成回调函数。

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

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