如何计算vscode扩展名文件夹中的文件?

时间:2020-10-25 11:24:44

标签: typescript vscode-extensions

我如何计算vscode扩展名文件夹中的文件并从资源管理器的上下文菜单中执行它?

2 个答案:

答案 0 :(得分: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() {}

...这是package.json中的重要部分:

"contributes": {
    "commands": [
        {
            "command": "MMA.countFiles",
            "title": "_count.Files"
        }
    ],
    "menus": {
        "explorer/context": [
            {
                "when": "explorerResourceIsFolder",
                "command": "MMA.countFiles",
                "group": "navigation@98"
            }
        ]
    }   
},

答案 1 :(得分:1)

我认为您可以使用glob轻松完成此操作。例如

const glob = require('glob');

const files = glob.sync('./js/**/*.*', {'nodir': true}); // returns an array of files

console.log(files);
console.log(files.length);

其中./js是递归计数文件的文件夹。如果要考虑dot(点文件),则还有一个.files选项。

递归,不计算文件夹数和构建数组都由一行代码为您完成。