2

我想将多个文件从源目录移动到目标目录。

我尝试了多个包,但它移动了文件夹本身。但我想将源目录中包含的文件移到目标目录中。

mv('/opt/output/', '/opt/sentFiles' ,function(err) {
    var destination = path.join( '/opt/sentFiles',files[i])
}); 

我尝试了 child_process 然后 mv 包。mv 包正在工作,但是。它将源文件夹本身移动到目标文件夹。实际上我想从源文件夹 exp output/* sentfile/* 中移动文件

4

2 回答 2

3

您可以使用模块简单地实现这一点fs,理想情况下,您所要做的就是使用重命名功能表单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

希望能帮助到你!

于 2018-10-16T04:53:41.337 回答
0

使用fs-jetpack可以轻松完成此任务:

const jetpack = require("fs-jetpack");

const src = jetpack.cwd("path/to/source/folder");
const dst = jetpack.cwd("path/to/destination/folder");

// Here assuming we want to move all .txt files, but 
// of corse this can be configured in any way.
src.find({ matching: "*.txt" }).forEach(filePath => {
  src.move(filePath, dst.path(filePath));
});
于 2021-12-01T13:16:26.517 回答