Help us understand the problem. What is going on with this article?

TypeScriptでファイル、ディレクトリ検索

More than 1 year has passed since last update.

目的

TypeScriptでファイル、ディレクトリ検索を行うプログラムの備忘録。
Node.jsで検索すれば有益な情報は見つけられますし書き方ほぼ同一ですが、
TypeScriptで逆引き検索している方など、お役に立てれば幸いです。

概要

対象のディレクトリを指定し、サブディレクトリ含めて指定した拡張子のファイルを一覧として出力する。

npm インストール

ファイル検索、ディレクトリ検索に必要なモジュールをインストール
npm install --save @types/node

サンプルコード

import * as fs from "fs";
import * as path from "path";

// 検索したいディレクトリ
var seekBaseDir = "C:\\Users\\";
// 対象ファイルの拡張子
var extFilter = "sln";

function extension(element: string) {
    var extName = path.extname(element);
    return extName === '.' + extFilter;
};

function seekDir(dirpath: string) {
    fs.readdir(dirpath, function (err, list) {
        if (list !== undefined) {
            list.filter(extension).forEach(function (value) {
                console.log(dirpath + "\\" + value);
            });

            list.forEach(function (value) {
                let nextDir: string = dirpath + "\\" + value;
                if (fs.statSync(nextDir).isDirectory()) {
                    seekDir(nextDir);
                }
            });
        }
    });
}
// 検索開始
seekDir(seekBaseDir);

結果
C:\Users\YFurugen\Documents\wpf\based\XamDataGrid\Simple\Sample.sln
C:\Users\YFurugen\Documents\wpf\based\XamGrid\Simple\Sample\Sample.sln
C:\Users\YFurugen\Documents\xamarin\BlueMonkey\client\BlueMonkey\BlueMonkey.sln
C:\Users\YFurugen\Documents\xamarin\BlueMonkey\server\csharp\BlueMonkey.MobileApp\BlueMonkey.MobileApp.sln

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away