2

I want to move multiple files from source directory to destination directory.

I tried with multiple package but its moving the folder itself. but i would like to move one the files contain in the source directory into destination directory.

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

I tried for child_process then mv package. mv package is working but. its move source folder itself to destination folder. actually i want to move files from source folder exp output/* sentfile/*

jfriend00
  • 683,504
  • 96
  • 985
  • 979
Jay
  • 187
  • 2
  • 13

2 Answers2

3

You can simply achieve this using the fs module, ideally, you have to do is use the rename function form fs module. There is also a Synchronous version renameSync.

According to your requirements, all you have to do is get the list of files you wish to move and loop over to move(rename) them.

Following is the simple test code I tried to move a single file:

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

Hope it helps!

Vivek Molkar
  • 3,910
  • 1
  • 34
  • 46
1

This task can be done easily with 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));
});