As you see I use forEach statement twice in
fileList.forEach((file) => {
setFolder.forEach((folderName) => {
part.
At first I use for loop in setFolder part but it seems more awful.. So I change it to forEach statement again. But it looks something bad. I think there are better then this code. Any advices?
const fs = require("fs"); // Node.js file system module
const dir =
"G:\\google drive"; // set path
let setFolder = [
"A",
"B",
"C",
"D",
"E",
"F",
];
/* Create new folder name with setFolder array */
setFolder.forEach((folder) => {
if (!fs.existsSync(dir "\\complete\\" folder)) {
fs.mkdirSync(dir "\\complete\\" folder);
}
});
fs.readdir(dir, async function (error, fileList) {
if (error) {
console.log(error);
}
console.log(fileList);
fileList.forEach((file) => {
setFolder.forEach((folderName) => {
if (file.startsWith(folderName)) {
fs.rename(
dir "\\" file,
dir "\\complete\\" folderName "\\" file,
function (err) {
if (err) throw err;
console.log(`${file} move to ${folderName} complete`);
}
);
}
});
});
});
CodePudding user response:
I think that you can use the .find() method of Javascript array to find the file which starts with the folder name.
Example:
fileList.forEach((file) => {
const correspondingFolder = setFolder.find(folderName => file.startsWith(folderName));
if (correspondingFolder) {
// ....
}
});
Here is the complete docs of find() method: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/find