1

How do I count files in a folder in a vscode extension and execute it from the context menu in the explorer?

mortenma71
  • 898
  • 1
  • 8
  • 22

2 Answers2

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
  • 898
  • 1
  • 8
  • 22
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
  • 97,651
  • 19
  • 297
  • 324