node.js遍歷目錄的方法示例
更新時間:2018年08月01日 11:46:21 作者:fenerchen
本篇文章主要介紹了node.js遍歷目錄的方法示例,主要介紹了同步遍歷和異步遍歷兩種方法,非常具有實用價值,需要的朋友可以參考下
本文介紹了node.js遍歷目錄的方法示例,分享給大家,也給自己留個筆記,具體如下
同步遍歷
const fs = require('fs'); const path=require('path'); function travel(dir,callback){ fs.readdirSync(dir).forEach((file)=>{ var pathname=path.join(dir,file) if(fs.statSync(pathname).isDirectory()){ travel(pathname,callback) }else{ callback(pathname) } }) } travel('F:/HTML/Node/test',function(pathname){ console.log(pathname) })
異步遍歷
const fs = require('fs'); const path=require('path'); function travel(dir,callback){ fs.readdir(dir,(err,files)=>{ if(err){ console.log(err) }else{ files.forEach((file)=>{ var pathname=path.join(dir,file) fs.stat(pathname,(err,stats)=>{ if(err){ console.log(err) }else if(stats.isDirectory()){ travel(pathname,callback) }else{ callback(pathname) } }) }) } }) } travel('F:/HTML/Node/test',function(pathname){ console.log(pathname) })
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
Windows中安裝nvm進行Node版本控制與詳細使用教程
nvm和npm都是node.js版本管理工具,但是為了解決node各種不同之間版本存在不兼容的問題,因此可以通過nvm安裝和切換不同版本的node,感興趣的可以了解一下2023-09-09