我希望这会是一件简单的事,但我找不到任何可以做到的事情。
我只想获取给定文件夹/目录中的所有文件夹/目录。
例如:
<MyFolder>
|- SomeFolder
|- SomeOtherFolder
|- SomeFile.txt
|- SomeOtherFile.txt
|- x-directory
我希望得到一个数组:
["SomeFolder", "SomeOtherFolder", "x-directory"]
或上面的路径,如果它是如何服务...
上面已经存在的任何事情都可以做到吗?
答案 0 :(得分:360)
这是this answer的一个较短的同步版本,可以列出当前目录中的所有目录(隐藏或不隐藏):
const { lstatSync, readdirSync } = require('fs')
const { join } = require('path')
const isDirectory = source => lstatSync(source).isDirectory()
const getDirectories = source =>
readdirSync(source).map(name => join(source, name)).filter(isDirectory)
答案 1 :(得分:90)
感谢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
}
答案 2 :(得分:22)
使用路径列出目录。
function getDirectories(path) {
return fs.readdirSync(path).filter(function (file) {
return fs.statSync(path+'/'+file).isDirectory();
});
}
答案 3 :(得分:18)
我来到这里寻找一种方法来获取所有子目录及其所有子目录等。在accepted answer的基础上,我写道:
const fs = require('fs');
const path = require('path');
function flatten(lists) {
return lists.reduce((a, b) => a.concat(b), []);
}
function getDirectories(srcpath) {
return fs.readdirSync(srcpath)
.map(file => path.join(srcpath, file))
.filter(path => fs.statSync(path).isDirectory());
}
function getDirectoriesRecursive(srcpath) {
return [srcpath, ...flatten(getDirectories(srcpath).map(getDirectoriesRecursive))];
}
答案 4 :(得分:10)
这应该这样做:
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}));
}
}
});
}
答案 5 :(得分:6)
或者,如果您能够使用外部库,则可以使用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);
有关详细信息(和示例),请查看文档:{{3}}
免责声明:我是作者。
答案 6 :(得分:4)
在node.js版本> = v10.13.0的情况下,如果将withFileTypes
选项设置为true
,则fs.readdirSync将返回fs.Dirent对象的数组。
因此您可以使用
const fs = require('fs')
const directories = source => fs.readdirSync(source, {
withFileTypes: true
}).reduce((a, c) => {
c.isDirectory() && a.push(c.name)
return a
}, [])
答案 7 :(得分:3)
getDirectories的异步版本,你需要async module:
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);
});
}
答案 8 :(得分:3)
使用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("/")
答案 9 :(得分:2)
var getDirectories = (rootdir , cb) => {
fs.readdir(rootdir, (err, files) => {
if(err) throw err ;
var dirs = files.map(filename => path.join(rootdir,filename)).filter( pathname => fs.statSync(pathname).isDirectory());
return cb(dirs);
})
}
getDirectories( myDirectories => console.log(myDirectories));``
答案 10 :(得分:1)
使用 fs,路径模块可以获取该文件夹。这个用Promise。如果您将获得填充,您可以将 isDirectory()更改为 isFile() Nodejs--fs--fs.Stats。最后,您可以获取文件&#39;名称文件& #39; extname等Nodejs---Path
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);
});
});
答案 11 :(得分:1)
此答案未使用诸如readdirSync
或statSync
之类的阻塞函数。它不使用外部依赖项,也不在回调地狱的深处发现自己。
相反,我们使用现代JavaScript便利性,例如Promises和async-await
语法。异步结果被并行处理;不按顺序-
const { readdir, stat } =
require ("fs") .promises
const { join } =
require ("path")
const dirs = async (path = ".") =>
(await stat (path)) .isDirectory ()
? Promise
.all
( (await readdir (path))
.map (p => dirs (join (path, p)))
)
.then
( results =>
[] .concat (path, ...results)
)
: []
我将安装一个示例程序包,然后测试我们的功能-
$ npm install ramda
$ node
让我们看看它的工作原理-
> dirs (".") .then (console.log, console.error)
[ '.'
, 'node_modules'
, 'node_modules/ramda'
, 'node_modules/ramda/dist'
, 'node_modules/ramda/es'
, 'node_modules/ramda/es/internal'
, 'node_modules/ramda/src'
, 'node_modules/ramda/src/internal'
]
使用通用模块Parallel
,我们可以简化dirs
的定义-
const Parallel =
require ("./Parallel")
const dirs = async (path = ".") =>
(await stat (path)) .isDirectory ()
? Parallel (readdir (path))
.flatMap (f => dirs (join (path, f)))
.then (results => [ path, ...results ])
: []
上面使用的Parallel
模块是从一组旨在解决类似问题的函数中提取的模式。有关更多说明,请参见此related Q&A。
答案 12 :(得分:1)
如果您需要使用所有async
版本。你可以有这样的东西。
记录目录长度,将其用作指示器,以判断是否所有异步统计任务都已完成。
如果异步统计任务完成,则已检查所有文件统计信息,因此请调用回调
只有Node.js是单线程才会有效,因为它假定没有两个异步任务会同时增加计数器。
'use strict';
var fs = require("fs");
var path = require("path");
var basePath = "./";
function result_callback(results) {
results.forEach((obj) => {
console.log("isFile: " + obj.fileName);
console.log("fileName: " + obj.isFile);
});
};
fs.readdir(basePath, (err, files) => {
var results = [];
var total = files.length;
var finished = 0;
files.forEach((fileName) => {
// console.log(fileName);
var fullPath = path.join(basePath, fileName);
fs.stat(fullPath, (err, stat) => {
// this will work because Node.js is single thread
// therefore, the counter will not increment at the same time by two callback
finished++;
if (stat.isFile()) {
results.push({
fileName: fileName,
isFile: stat.isFile()
});
}
if (finished == total) {
result_callback(results);
}
});
});
});
正如你所看到的,这是一种“深度优先”的方法,这可能导致回调地狱,并且它不是很“功能性”。人们试图通过将异步任务包装到Promise对象中来解决Promise这个问题。
'use strict';
var fs = require("fs");
var path = require("path");
var basePath = "./";
function result_callback(results) {
results.forEach((obj) => {
console.log("isFile: " + obj.fileName);
console.log("fileName: " + obj.isFile);
});
};
fs.readdir(basePath, (err, files) => {
var results = [];
var total = files.length;
var finished = 0;
var promises = files.map((fileName) => {
// console.log(fileName);
var fullPath = path.join(basePath, fileName);
return new Promise((resolve, reject) => {
// try to replace fullPath wil "aaa", it will reject
fs.stat(fullPath, (err, stat) => {
if (err) {
reject(err);
return;
}
var obj = {
fileName: fileName,
isFile: stat.isFile()
};
resolve(obj);
});
});
});
Promise.all(promises).then((values) => {
console.log("All the promise resolved");
console.log(values);
console.log("Filter out folder: ");
values
.filter((obj) => obj.isFile)
.forEach((obj) => {
console.log(obj.fileName);
});
}, (reason) => {
console.log("Not all the promise resolved");
console.log(reason);
});
});
答案 13 :(得分:1)
CoffeeScript版this answer,具有正确的错误处理功能:
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
取决于async
或者,use a module for this! (有一切模块。[需要引证])
答案 14 :(得分:0)
感谢Mayur认识我withFileTypes
。我编写了以下代码来递归获取特定文件夹的文件。可以轻松地修改它以仅获取目录。
const getFiles = (dir, base = '') => readdirSync(dir, {withFileTypes: true}).reduce((files, file) => {
const filePath = path.join(dir, file.name)
const relativePath = path.join(base, file.name)
if(file.isDirectory()) {
return files.concat(getFiles(filePath, relativePath))
} else if(file.isFile()) {
file.__fullPath = filePath
file.__relateivePath = relativePath
return files.concat(file)
}
}, [])
答案 15 :(得分:0)
函数式编程
const fs = require('fs')
const path = require('path')
const R = require('ramda')
const getDirectories = pathName => {
const isDirectory = pathName => fs.lstatSync(pathName).isDirectory()
const mapDirectories = pathName => R.map(name => path.join(pathName, name), fs.readdirSync(pathName))
const filterDirectories = listPaths => R.filter(isDirectory, listPaths)
return {
paths:R.pipe(mapDirectories)(pathName),
pathsFiltered: R.pipe(mapDirectories, filterDirectories)(pathName)
}
}
答案 16 :(得分:0)
万一其他人从网络搜索结束到此处,并且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);
}
答案 17 :(得分:0)
带有ES6的完全异步版本,只有本地软件包fs.promises和async / await并行执行文件操作:
const fs = require('fs');
const path = require('path');
async function listDirectories(rootPath) {
const fileNames = await fs.promises.readdir(rootPath);
const filePaths = fileNames.map(fileName => path.join(rootPath, fileName));
const filePathsAndIsDirectoryFlagsPromises = filePaths.map(async filePath => ({path: filePath, isDirectory: (await fs.promises.stat(filePath)).isDirectory()}))
const filePathsAndIsDirectoryFlags = await Promise.all(filePathsAndIsDirectoryFlagsPromises);
return filePathsAndIsDirectoryFlags.filter(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.isDirectory)
.map(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.path);
}
经过测试,效果很好。
答案 18 :(得分:0)
您可以使用以下模块来帮助自己:
它有很多选择。您可以使用以下代码:
const dree = require('dree');
const options = {
depth: 1
};
const fileCallback = function() {};
const directories = [];
const dirCallback = function(dir) {
directories.push(dir.name);
};
dree.scan('./dir', {});
console.log(directories);
将打印指定路径(“ ./dir”)的直接子目录。
如果不放置选项depth: 1
,甚至可以递归方式获取所有目录,不仅是指定路径的有向子级。
答案 19 :(得分:0)
安装
npm i graph-fs
使用
const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");
const names = directory.children // <--
.filter(node => node.is.directory)
.map(directory => directory.name);
答案 20 :(得分:-1)
异步/等待变体:
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。