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


当前回答

对于8.0.0以上的Node版本使用承诺:

const {promisify} = require('util');
const fs = require('fs');
const {join} = require('path');
const mv = promisify(fs.rename);

const moveThem = async () => {
  // Move file ./bar/foo.js to ./baz/qux.js
  const original = join(__dirname, 'bar/foo.js');
  const target = join(__dirname, 'baz/qux.js'); 
  await mv(original, target);
}

moveThem();

其他回答

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

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

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

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

fs.renameSync(oldPath, newPath)

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