Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

Node fs.readdir 读取文件顺序代码求解惑

最近在对 Node 中 fs.readdir 进行调试,其中读取出来的数组文件顺序不是按寻常的字母序来排列,就进行了一些搜索
看到下面的代码中


function compareFiles(a,b) {
    return b.isDirectory() - a.isDirectory() || a.name > b.name ? 1 : -1
  }

fs.readdir(currentDir, { withFileTypes: true }, function (err, items) {
    items.sort(compareFiles);
    for (var i = 0; i < items.length; i++) {
        if (!items[i].name.startsWith(".")) {
            if (items[i].isFile()) {
               //append file name somewhere
            } else {
               //append directory name somewhere
            }
        }
    }
});

出处 fs.readdirSync目录优先

想问 return b.isDirectory() - a.isDirectory() || a.name > b.name ? 1 : -1 这一句是什么意思,怎么运行的


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

b.isDirectory() - a.isDirectory() 返回的是 truefalse 可用来计算

      true  -  true  //  0
      false - false  //  0
      true  -  false //  1
      false - true   // -1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...