我希望这会是一件简单的事情,但我找不到任何可以做到的事情。
我只想获取给定文件夹/目录中的所有文件夹/目录。
例如:
< MyFolder文件>| - S’
为了防万一其他人从网络搜索结束这里,并且Grunt已经在他们的依赖列表中,对此的答案变得微不足道。这是我的解决方案:
/** * Return all the subfolders of this path * @param {String} parentFolderPath - valid folder path * @param {String} glob ['/*'] - optional glob so you can do recursive if you want * @returns {String[]} subfolder paths */ getSubfolders = (parentFolderPath, glob = '/*') => { return grunt.file.expand({filter: 'isDirectory'}, parentFolderPath + glob); }
和getDirectories的异步版本,你需要 异步模块 为了这:
var fs = require('fs'); var path = require('path'); var async = require('async'); // https://github.com/caolan/async // Original function function getDirsSync(srcpath) { return fs.readdirSync(srcpath).filter(function(file) { return fs.statSync(path.join(srcpath, file)).isDirectory(); }); } function getDirs(srcpath, cb) { fs.readdir(srcpath, function (err, files) { if(err) { console.error(err); return cb([]); } var iterator = function (file, cb) { fs.stat(path.join(srcpath, file), function (err, stats) { if(err) { console.error(err); return cb(false); } cb(stats.isDirectory()); }) } async.filter(files, iterator, cb); }); }
感谢JavaScript ES6(ES2015)语法功能,它是一个内容:
**同步版**
const { readdirSync, statSync } = require('fs') const { join } = require('path') const dirs = p => readdirSync(p).filter(f => statSync(join(p, f)).isDirectory())
的 Node.js 10+的异步版本(实验性) 强>
const { readdir, stat } = require("fs").promises const { join } = require("path") const dirs = async path => { let dirs = [] for (const file of await readdir(path)) { if ((await stat(join(path, file))).isDirectory()) { dirs = [...dirs, file] } } return dirs }
使用路径列出目录。
function getDirectories(path) { return fs.readdirSync(path).filter(function (file) { return fs.statSync(path+'/'+file).isDirectory(); }); }
这应该这样做:
的 CoffeeScript(同步) 强>
fs = require 'fs' getDirs = (rootDir) -> files = fs.readdirSync(rootDir) dirs = [] for file in files if file[0] != '.' filePath = "#{rootDir}/#{file}" stat = fs.statSync(filePath) if stat.isDirectory() dirs.push(file) return dirs
的 CoffeeScript(异步) 强>
fs = require 'fs' getDirs = (rootDir, cb) -> fs.readdir rootDir, (err, files) -> dirs = [] for file, index in files if file[0] != '.' filePath = "#{rootDir}/#{file}" fs.stat filePath, (err, stat) -> if stat.isDirectory() dirs.push(file) if files.length == (index + 1) cb(dirs)
的 JavaScript(异步) 强>
var fs = require('fs'); var getDirs = function(rootDir, cb) { fs.readdir(rootDir, function(err, files) { var dirs = []; for (var index = 0; index < files.length; ++index) { var file = files[index]; if (file[0] !== '.') { var filePath = rootDir + '/' + file; fs.stat(filePath, function(err, stat) { if (stat.isDirectory()) { dirs.push(this.file); } if (files.length === (this.index + 1)) { return cb(dirs); } }.bind({index: index, file: file})); } } }); }
或者,如果您能够使用外部库,则可以使用 filehound 。它支持回调,承诺和同步调用。
filehound
的 使用承诺: 强>
const Filehound = require('filehound'); Filehound.create() .path("MyFolder") .directory() // only search for directories .find() .then((subdirectories) => { console.log(subdirectories); });
的 使用回调: 强>
const Filehound = require('filehound'); Filehound.create() .path("MyFolder") .directory() .find((err, subdirectories) => { if (err) return console.error(err); console.log(subdirectories); });
的 同步通话: 强>
const Filehound = require('filehound'); const subdirectories = Filehound.create() .path("MyFolder") .directory() .findSync(); console.log(subdirectories);
有关更多信息(和示例),请查看文档: https://github.com/nspragg/filehound
免责声明:我是作者。
使用fs-extra,它承诺异步fs调用,以及新的等待异步语法:
const fs = require("fs-extra"); async function getDirectories(path){ let filesAndDirectories = await fs.readdir(path); let directories = []; await Promise.all( filesAndDirectories.map(name =>{ return fs.stat(path + name) .then(stat =>{ if(stat.isDirectory()) directories.push(name) }) }) ); return directories; } let directories = await getDirectories("/")
CoffeeScript版 这个答案 ,正确的错误处理:
fs = require "fs" {join} = require "path" async = require "async" get_subdirs = (root, callback)-> fs.readdir root, (err, files)-> return callback err if err subdirs = [] async.each files, (file, callback)-> fs.stat join(root, file), (err, stats)-> return callback err if err subdirs.push file if stats.isDirectory() callback null (err)-> return callback err if err callback null, subdirs
依赖于取决于 异步
或者, 为此使用一个模块! (有一切模块。[引证需要])
使用 的 FS銆乸ATH 强> 模块可以得到文件夹。这个用Promise。如果你的意志得到填补,你可以改变 的 的isdirectory() 强> 至 的 ISFILE() 强> 的NodeJS - FS - fs.Stats 最后,你可以得到文件'name file'extname等等 ---的NodeJS路径
var fs = require("fs"), path = require("path"); //your <MyFolder> path var p = "MyFolder" fs.readdir(p, function (err, files) { if (err) { throw err; } //this can get all folder and file under <MyFolder> files.map(function (file) { //return file or folder path, such as **MyFolder/SomeFile.txt** return path.join(p, file); }).filter(function (file) { //use sync judge method. The file will add next files array if the file is directory, or not. return fs.statSync(file).isDirectory(); }).forEach(function (files) { //The files is array, so each. files is the folder name. can handle the folder. console.log("%s", files); }); });
我个人会在循环中声明stat函数 - 就像这样:
function getSubDirs(dir, cb) { fs.readdir(dir, function(err, files) { var dirs = [], filePath, checkDirectory = function(err, stat) { if(stat.isDirectory()) { dirs.push(files[i]); } if(i + 1 === l) { // last record cb(dirs); } }; for(var i=0, l=files.length; i<l; i++) { if(files[i][0] !== '.') { // ignore hidden filePath = dir+'/'+files[i]; fs.stat(filePath, checkDirectory); } } }); }
JShint另有抱怨,你可能会在每个循环传递上创建一个新的函数调用。
异步/等待变体:
async function getFolders(path) { let result = Array(); let files = await fs.readdir(path); for (let i = 0; i < files.length; i++) { var filePath = path + '/' + file; if (await fs.stat(filePath).isDirectory()) { result.push(filePath); } } return result; }
我也建议使用 FS-EXTRA 而不是fs ..