node.js遍歷目錄的方法示例
更新時(shí)間:2018年08月01日 11:46:21 作者:fenerchen
本篇文章主要介紹了node.js遍歷目錄的方法示例,主要介紹了同步遍歷和異步遍歷兩種方法,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
本文介紹了node.js遍歷目錄的方法示例,分享給大家,也給自己留個(gè)筆記,具體如下
同步遍歷
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)
})
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
Windows中安裝nvm進(jìn)行Node版本控制與詳細(xì)使用教程
nvm和npm都是node.js版本管理工具,但是為了解決node各種不同之間版本存在不兼容的問題,因此可以通過nvm安裝和切換不同版本的node,感興趣的可以了解一下2023-09-09
NodeJS學(xué)習(xí)筆記之Connect中間件模塊(二)
本文續(xù)上文的內(nèi)容,介紹下nodejs中connect中間件的使用方式及用途,希望大家喜歡。2015-01-01

