Front2End
  • Introduction
  • Front
    • Introduction
    • 新手入門
    • 相關連結
    • Css
    • Javascript
    • 立即函式
    • Google SpreadSheet 當資料庫
    • 資料視覺化
    • 新年快樂
    • Google御用網頁語言 Node.js
    • 世大運網頁遊戲腳本
    • YDNJS-1.Up&Going
    • YDNJS
    • 新手入門
  • 實做
    • 程式碼片段蒐集
    • 爬蟲
    • 實做: 貪吃蛇
    • 練習: z=ax+by
    • 實做: 爬八卦版的文章
    • LearnYouNode
      • 3 - 同步 IO 讀寫
      • 4 – My First Async I\/O
      • 5 - filter
      • 6 - Make it Modular
      • 7-Http Client
    • road_to_bookdown
    • FreeCodeCamp
  • End
    • node.js
Powered by GitBook
On this page

Was this helpful?

  1. 實做
  2. LearnYouNode

5 - filter

Previous4 – My First Async I\/ONext6 - Make it Modular

Last updated 5 years ago

Was this helpful?

我竟然靠自己查文件完成這個功能了,覺得開心

  • 列出目錄下所有檔案:

  • 挖出後綴名:

附上自己寫的程式碼

// filter
// node 4-filter.js path subname

var fs = require("fs")
var dir = process.argv[2]
var subname = process.argv[3]
var path = require("path")

// get files list in dir
fs.readdir(dir, function(err, list) {


    // if path.extname = subname
    // log it

    for(i=0; i<=list.length; i++){
        if(path.extname(list[i]) == ("."+subname) ){
            console.log(list[i])    
         }      
    }

} );

官方的解答 主要差異在官方用 Array.foreach(function callback(value, index, array) ) 來代表迴圈

var fs = require('fs')
var path = require('path')

var folder = process.argv[2]
var ext = '.' + process.argv[3]

fs.readdir(folder, function (err, files) {
  if (err) return console.error(err)
  files.forEach(function(file) {
      if (path.extname(file) === ext) {
          console.log(file)
      }
  })
})
[Node.js] 學習筆記:使用 readdir() 尋訪目錄下所有檔案
Node.js Path 模塊 | 菜鳥教程