0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

初心者|node.jsのREPLでファイルをリネーム

Posted at

以前に初心者|node.jsでリネーム。フォルダからファイル名一覧を取得し一括変更するという記事を書きました。

でも「いちいちファイルを作成して実行するのは面倒やなぁ」と思い、node.jsのREPL(リプル)で実行することにしました。

今回したかったことは、あるディレクトリ内にある複数の画像ファイルの名称を一括で変更することです。変更した名称には連番もつけます。

要件

  • node.js がインストールされている
  • node.jsのREPLを使いたい
  • 特定のフォルダ内のファイルを一括リネームしたい
  • ファイル名に連番もつけたい
  • 対象のファイルを種類(拡張子)で抽出したい(フィルタリングしたい)

image.png

リネーム前 リネーム後
IMG_xxxx.jpg newFileName-●.jpg
  • リネーム前の名称は何でもいい
  • は連番

そもそもMACには、一括リネーム機能がついています

image.png
image.png

  • 対象ファイルを選択して、右クリック
  • ●項目の名前を変更... をクリック
  • あとは、よしなに...

本題

1)ターミナルを起動する

image.png

  • リネームするファイルがあるディレクトリでターミナルを開いてください
  • (例) imeges ディレクトリ内に 24個の jpgファイルがあります

 

2)REPLの起動

image.png

terminal
$ node
  • node + エンターキーでnode.jsのREPLが起動します

3)モジュール読み込み

image.png

REPL(node.js)
$ const fs = require("fs"),
  path = require("path");
  • nodeのモジュールfspath を読み込みます。

4)ファイル名の取得

image.png

REPL(node.js)
$ const dir = "./",
  fileNameList = fs.readdirSync(dir),
  filteredFileNames = fileNameList.filter(RegExp.prototype.test, /.*\.jpg$/);
  • dir = "./" では、カレントディレクトリをセットしています
  • fileNameList = fs.readdirSync(dir)で、カレントディレクトリ内のファイル名一式を取得しています(この時点では隠しファイルなどjpg以外のファイルも読み込んでいます)。
  • filteredFileNames = fileNameList.filter(RegExp.prototype.test, /.*\.jpg$/) で、jpgファイルに絞っています(jpg以外のファイルを捨てています)。jpg以外のファイルをリネームする場合は\.jpgを任意の拡張子に書き換えてください。

5)変更後のファイル名を設定

image.png

REPL(node.js)
$ const newName = "newFileName-";
$ let i = 1;
  • newName = "newFileName-" で、新しいファイル名をセットしています。任意に書き換えてください。
  • i = 1 は、ファイル名に付与する連番のスタート値です

6)ファイル名の一括変更

image.png

REPL(node.js)
$ filteredFileNames.forEach((fileName) => {
    const filePath = {};
    filePath.before = path.join(dir, fileName);
    filePath.after = path.join(dir, newName + i + ".jpg");
    fs.rename(filePath.before, filePath.after, (err) => {
      if (err) throw err;
      console.log(filePath.before + " -> " + filePath.after);
    });
    i++;
  });
  • filePath.after = path.join(dir, newName + i + ".jpg") でリネーム後のファイル名(名称+連番)をセットしています。
  • 拡張子を忘れないように、ご注意ください。
  • i++;を忘れると、全ファイルが同じ名称 = ファイルが1つだけになるので、ご注意ください

image.png

リネームができれば成功です。

7)REPLの終了

REPL(node.js)上で キーcontrol + c を2回するとREPLが終了できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?