标签:error files func throw walk contents callback reac add
1
var fs = require("fs"), path = require("path"); function walk(dir, callback) { fs.readdir(dir, function(err, files) { if (err) throw err; files.forEach(function(file) { var filepath = path.join(dir, file); fs.stat(filepath, function(err,stats) { if (stats.isDirectory()) { walk(filepath, callback); } else if (stats.isFile()) { callback(filepath, stats); } }); }); }); }
2
import fs from ‘fs‘; import path from ‘path‘; function walk(dir) { return new Promise((resolve, reject) => { fs.readdir(dir, (error, files) => { if (error) { return reject(error); } Promise.all(files.map((file) => { return new Promise((resolve, reject) => { const filepath = path.join(dir, file); fs.stat(filepath, (error, stats) => { if (error) { return reject(error); } if (stats.isDirectory()) { walk(filepath).then(resolve); } else if (stats.isFile()) { resolve(filepath); } }); }); })) .then((foldersContents) => { resolve(foldersContents.reduce((all, folderContents) => all.concat(folderContents), [])); }); }); }); }
es6版本
const fs = require(‘fs‘).promises; const path = require(‘path‘); async function walk(dir) { let files = await fs.readdir(dir); files = await Promise.all(files.map(async file => { const filePath = path.join(dir, file); const stats = await fs.stat(filePath); if (stats.isDirectory()) return walk(filePath); else if(stats.isFile()) return filePath; })); return files.reduce((all, folderContents) => all.concat(folderContents), []); }
标签:error files func throw walk contents callback reac add
原文地址:https://www.cnblogs.com/wolbo/p/11872788.html