如何在 node.js 中移动文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8579055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I move files in node.js?
提问by rizidoro
How can I move files (like mv command shell) on node.js? Is there any method for that or should I read a file, write to a new file and remove older file?
如何在 node.js 上移动文件(如 mv 命令外壳)?有什么方法可以解决这个问题,还是我应该读取文件,写入新文件并删除旧文件?
回答by rizidoro
According to seppo0010 comment, I used the rename function to do that.
根据 seppo0010 评论,我使用重命名功能来做到这一点。
http://nodejs.org/docs/latest/api/fs.html#fs_fs_rename_oldpath_newpath_callback
http://nodejs.org/docs/latest/api/fs.html#fs_fs_rename_oldpath_newpath_callback
fs.rename(oldPath, newPath, callback)
Added in: v0.0.2
oldPath <String> | <Buffer> newPath <String> | <Buffer> callback <Function>Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.
fs.rename(oldPath, newPath, 回调)
加入:v0.0.2
oldPath <String> | <Buffer> newPath <String> | <Buffer> callback <Function>异步重命名(2)。除了可能的异常之外,没有为完成回调提供任何参数。
回答by Teoman shipahi
This example taken from: Node.js in Action
这个例子取自:Node.js in Action
A move() function that renames, if possible, or falls back to copying
一个 move() 函数,如果可能,重命名或回退到复制
var fs = require('fs');
module.exports = function move(oldPath, newPath, callback) {
fs.rename(oldPath, newPath, function (err) {
if (err) {
if (err.code === 'EXDEV') {
copy();
} else {
callback(err);
}
return;
}
callback();
});
function copy() {
var readStream = fs.createReadStream(oldPath);
var writeStream = fs.createWriteStream(newPath);
readStream.on('error', callback);
writeStream.on('error', callback);
readStream.on('close', function () {
fs.unlink(oldPath, callback);
});
readStream.pipe(writeStream);
}
}
回答by andrewrk
回答by Hani
Using nodejs natively
原生使用 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!')
})
(NOTE: "This will not work if you are crossing partitions or using a virtual filesystem not supporting moving files. [...]"– Flavien Volken Sep 2 '15 at 12:50")
(注意:“如果您跨分区或使用不支持移动文件的虚拟文件系统,这将不起作用。[...]”– Flavien Volken 2015 年 9 月 2 日 12:50”)
回答by deadrunk
util.pumpis deprecated in node 0.10 and generates warning message
util.pump在节点 0.10 中已弃用并生成警告消息
util.pump() is deprecated. Use readableStream.pipe() instead
So the solution for copying files using streams is:
所以使用流复制文件的解决方案是:
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 */ });
回答by iulia
Using the rename function:
使用重命名功能:
fs.rename(getFileName, __dirname + '/new_folder/' + getFileName);
where
在哪里
getFilename = file.extension (old path)
__dirname + '/new_folder/' + getFileName
assumming that you want to keep the file name unchanged.
假设您要保持文件名不变。
回答by mikeym
The fs-extramodule allows you to do this with it's move()method. I already implemented it and it works well if you want to completely move a file from one directory to another - ie. removing the file from the source directory. Should work for most basic cases.
该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!")
})
回答by alessioalex
Here's an example using util.pump, from >> How do I move file a to a different partition or device in Node.js?
这是使用 util.pump 的示例,来自 >>如何将文件 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');
});
回答by vorillaz
Using promises for Node versions greater than 8.0.0:
对大于 8.0.0 的 Node 版本使用 promise:
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();
回答by Jem
Just my 2 cents as stated in the answer above: The copy() method shouldn't be used as-is for copying files without a slight adjustment:
只是我的 2 美分,如上面的答案所述: copy() 方法不应该按原样用于复制文件而无需稍作调整:
function copy(callback) {
var readStream = fs.createReadStream(oldPath);
var writeStream = fs.createWriteStream(newPath);
readStream.on('error', callback);
writeStream.on('error', callback);
// Do not callback() upon "close" event on the readStream
// readStream.on('close', function () {
// Do instead upon "close" on the writeStream
writeStream.on('close', function () {
callback();
});
readStream.pipe(writeStream);
}
The copy function wrapped in a Promise:
包装在 Promise 中的 copy 函数:
function copy(oldPath, newPath) {
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(oldPath);
const writeStream = fs.createWriteStream(newPath);
readStream.on('error', err => reject(err));
writeStream.on('error', err => reject(err));
writeStream.on('close', function() {
resolve();
});
readStream.pipe(writeStream);
})
However, keep in mind that the filesystem might crash if the target folder doesn't exist.
但是,请记住,如果目标文件夹不存在,文件系统可能会崩溃。

