LoginSignup
0
2

指定したファイルに指定した文字列を追記するJavaScript

Last updated at Posted at 2024-01-10

指定したファイルに指定した文字列を追記するJavaScript

たくさんのHTMLファイルに、規定の文字列を差し込みたい要望があったので作成。

たとえば、ある注釈テキストのHTMLコードを、たくさんのHTMLファイルに差し込みたい、など。

数ページの対象のファイル数でのみテストしたので、大量だと動作保証できないです。

検証環境

  • MacOS 13.5.1
  • node v14.20.0

JS

index.js
const fs = require('fs');
const readline = require('readline');

//
// ファイルの存在チェック
// 1: ファイルパス
const isExist = (filePath) =>  {
  let ret = false;
  try {
    fs.statSync(filePath);
    ret = true;
  } catch(err) {
    ret = false;
    throw new Error("ファイルが見つかりません " + filePath);
  }
  return ret;
}

//
// ファイル読み込み処理
// 1: ファイルパス
// 2: エンコードの種類(デフォルト UTF-8)
const read = (filePath,encodestr) => {
  let content = new String();
  if(!encodestr){
    encodestr = "utf-8";
  }
  
  if(isExist(filePath)) {;
    content = fs.readFileSync(filePath, encodestr);
  }
  return content;

}

// パラメータ
// 1: パーツ部品のファイル
// 2: パーツを入れるファイルのパスがリスト化されたファイルリスト
// 3: パーツをいれたい場所に入れたキーワード(置き換え用の文字列、正規表現を使用しているので()[]{}などの記号前にはエスケープ文字をいれる)
// 例 node index.js part.txt filelist.txt "changestrings20230105"
try{
  // パラメータ取得
  const args = process.argv.slice(2);
  // パラメータ分割
  const partspath = args[0]
  const filelist = args[1]
  const targetPoint = args[2]

  console.log('parts ' + partspath)
  console.log('replace ' + filelist)
  console.log('targetPoint ' + targetPoint)

  if(!targetPoint){
    throw new Error("置き換える対象の文字列を入力してください");
  }

  // パーツ部品の読み込み
  const parts = read(partspath, 'utf-8');
  // ファイルリストは1行ずつ読み込むストリーム作成
  const stream = fs.createReadStream(filelist);  
  stream.on("error", (err) => console.log("エラーが発生しました " + err));
  // ファイルリストの読み込み
  const reader = readline.createInterface({ input: stream });
  reader.on('line', targetFilePath => {
    let data = read(targetFilePath, 'utf-8');
    const replaced = data.replace(new RegExp(targetPoint,'g'), parts);
    fs.writeFileSync(targetFilePath, replaced);
  });
  
}catch(err){
  console.log("エラーが起きました " + err);
}

操作方法

1. ファイルリストをつくる

差し込む対象のファイルパスの一覧ファイルを用意する
(index.jsと同じディレクトリにおくと実行しやすい)

1行1ファイルパス

filelist.txt
/hoge/hoge/index.html
/hoge/hoge/hoge/index.html
/hoge/hoge/hoge/sample.html

2. 差し込む対象の各ファイルに差し込み位置がわかる文字列をいれる

文字列はなんでもよい、既存のソースには存在ない文字列がよい

/hoge/hoge/index.html
<div>元あるHTMLコード...</div>

[kokonisashikomi]

<div>元あるHTMLコード...</div>

3. パーツ用のファイルをつくる

差し込む文字列のみがはいったファイルをつくる
(index.jsと同じディレクトリにおくと実行しやすい)

parts.html
<div>
<p>パーツ部分のテキスト</p>
</div>

4. コマンドラインでindex.jsのあるディレクトリへ移動

cd hoge/

5. 実行

パラメータ

  • 1: パーツ部品のファイルパス
  • 2: パーツを入れるファイルのパスがリスト化されたファイルリストのパス
  • 3: パーツをいれたい場所に入れたキーワード(置き換え用の文字列、ダブルコーテーションで囲う、正規表現を使用しているので()[]{}などの記号前にはエスケープ文字をいれる)
node index.js parts.html filelist.txt "\[kokonisashikomi\]"

6. 結果

/hoge/hoge/index.html
<div>元あるHTMLコード...</div>

<div>
<p>パーツ部分のテキスト</p>
</div>

<div>元あるHTMLコード...</div>
0
2
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
2