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


当前回答

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

其他回答

本地使用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)

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

使用rename函数:

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

在哪里

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

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

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

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

fs.renameSync(oldPath, newPath)