Welcome to OGeek Q&A 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 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...