我想将多个文件从源目录移动到目标目录。
我尝试使用多个包,但它移动了文件夹本身。但我想将源目录中包含的文件移动到目标目录中。
mv('/opt/output/', '/opt/sentFiles' ,function(err) {
var destination = path.join( '/opt/sentFiles',files[i])
});
我尝试了 child_process 然后 mv 包。 mv 包正在运行,但是。它将源文件夹本身移动到目标文件夹。实际上我想从源文件夹 exp output/* sentfile/* 移动文件
最佳答案
您可以使用 fs
模块简单地实现此目的,理想情况下,您所要做的就是使用 rename函数形式为 fs
模块。还有同步版本renameSync .
根据您的要求,您所要做的就是获取要移动的文件列表并循环移动(重命名)它们。
以下是我尝试移动单个文件的简单测试代码:
var fs = require('fs');
// Assuming all files are in same folder
let files = ['test1.txt', 'test2.txt', 'test3.txt'];
// I am using simple for, you can use any variant here
for (var i = files.length - 1; i >= 0; i--) {
var file = files[i];
fs.rename('./source/' + file, './dest/' + file, function(err) {
if (err) throw err;
console.log('Move complete.');
});
}
//-------------------------- OUTPUT --------------------------
// Directory Structure Before Move
.
├── dest
├── index.js
├── package.json
└── source
├── test1.txt
├── test2.txt
└── test3.txt
// Directory Structure After Move
.
├── dest
│ ├── test1.txt
│ ├── test2.txt
│ └── test3.txt
├── index.js
├── package.json
└── source
希望对你有帮助!
关于node.js - NodeJS 中多个文件移动到另一个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52827683/