如何在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)
推荐文章
- 在MacOS X上推荐用什么方式安装Node.js、nvm和npm ?
- 如何将Node.js流的内容读入字符串变量?
- 如何在node.js中移动文件?
- 如何修改文本文件?
- npm install和npm run build有什么区别?
- 使用async/await尝试/捕获块
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 有没有办法修复包锁。json lockfileVersion所以npm使用特定的格式?
- 如何使用npm全局安装一个模块?
- Python列表目录,子目录和文件
- 实时http流到HTML5视频客户端的最佳方法
- 使用node.js下载图像
- Node.js Express中的HTTP GET请求
- Node.js:将文本文件读入数组。(每一行都是数组中的一项。)
- 我如何知道我在S3桶中存储了多少对象?