How do I count files in a folder in a vscode extension and execute it from the context menu in the explorer?
Asked
Active
Viewed 1,386 times
3 Answers
1
import * as vscode from 'vscode';
const fs = require('fs');
export function walk(dir: string) {
// https://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search
// by Victor Powell: https://stackoverflow.com/users/786374/victor-powell
var results: string[] = [];
var list = fs.readdirSync(dir);
list.forEach(function(file: string) {
file = dir + '/' + file;
var stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
// fecurse into a subdirectory
results = results.concat(walk(file));
} else {
// is a file
results.push(file);
}
});
return results;
};
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('MMA.countFiles', async (e) => {
// The code you place here will be executed every time your command is executed
let files = walk(e.path);
vscode.window.showInformationMessage(`${files.length} files in ${e.path}`);
});
context.subscriptions.push(disposable);
}
export function deactivate() {}
...and this is the important part in package.json:
"contributes": {
"commands": [
{
"command": "MMA.countFiles",
"title": "_count.Files"
}
],
"menus": {
"explorer/context": [
{
"when": "explorerResourceIsFolder",
"command": "MMA.countFiles",
"group": "navigation@98"
}
]
}
},

mortenma71
- 1,078
- 2
- 9
- 27
1
I would think you could do it with glob pretty easily. For example
const glob = require('glob');
const files = glob.sync('./js/**/*.*', {'nodir': true}); // returns an array of files
console.log(files);
console.log(files.length);
where ./js
is the folder in which to recursively count files. There is also a dot
option if you have .files
(dotfiles) to consider.
The recursion, not counting folders, and building the array are all handled for you in one line of code.

Mark
- 143,421
- 24
- 428
- 436
-
Thanks - I use it in `gulp` quite a bit. – Mark Oct 25 '20 at 20:09
0
I had the same question. I did not find an extension for it, but this is how I did it on the command line (Counts the number of files in the validatorts
folder).
ls projects/fs-validatorts/src/lib/validators/ | wc -l

Ole
- 41,793
- 59
- 191
- 359