查找创建文件夹Nodejs的算法

时间:2018-03-30 17:04:27

标签: javascript node.js algorithm

我必须将图像保存在文件夹中。我从mysql中获取了id的图像,如果id小于1000,则必须创建文件夹1000,然后如果它小于100,则创建文件夹100等。然后2000等等。我应该怎么写这个?我可以使用if-else语句或switch来完成此操作,但这将是非常长的代码。求救!

1 个答案:

答案 0 :(得分:1)

在决定要创建的文件夹后使用fs.mkdir。

输入ID,然后获取父(kilo)文件夹,然后获取子文件夹的名称。

const ids = [100, 200, 1100, 1200, 4500];
//const fs = require("fs");

//parent folders
//map the ids and to decide which parent folder they go into e.g. 1000, 2000, 4000 ?
//use a new Set to only get the unique folders (don't create same folder more than once)
//get the array of this Set
const kilofolders = Array.from(new Set(ids.map(id => parseInt(((id/1000)+1))*1000)));

//sub folders
//loop the parent folders and return an array of the child folders
//by filtering the ids by whether is is <= the parent number e.g. 100 is <= 1000
//and whether it is > the parent number - 1000 e.g. within range
//then map the subfolder ids to change their names to just the < 1000 versions
const subfolders = kilofolders.map(kilo => (ids.filter(id => id <= kilo && id > kilo - 1000).map(id => id % 1000)));

//use fs-extra if you don't like callback hell
kilofolders.forEach((name, i)=>{
  /*
  fs.mkdir(`./${name}`, (err)=>{
    if(!err){
      console.log("created parent folder", name);
      subfolders[i].forEach((id)=>{
        fs.mkdir(`./${name}/${id}`, function(err){
          if(!err){
            console.log("created subfolder", id, "in", name);
          }
          return;
        });
      });
    }
    return;
  });
  */
  console.log(name, subfolders[i]);
  return;
});