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


当前回答

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

其他回答

节点.js v10.0.0+

const fs = require('fs')
const { promisify } = require('util')
const pipeline = promisify(require('stream').pipeline)

await pipeline(
  fs.createReadStream('source/file/path'),
  fs.createWriteStream('destination/file/path')
).catch(err => {
  // error handling
})
fs.unlink('source/file/path')

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

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

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

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