Node.js v12.18.0
2020.11.03(火)
相対パスを絶対パスに変換
path.resolve()
を使う
The path.resolve() method resolves a sequence of paths or path segments into an absolute path.
Path | Node.js v12.19.0 Documentationconst path = require('path'); let absolutePath = path.resolve('./test.txt'); // => /Users/.../test.txt (絶対パス)
共通処理を別ファイルでモジュール化
module.exports.add = function (v1, v2) { return v1 + v2; }; module.exports.minus = function (v1, v2) { return v1 - v2; };
共通処理内で再帰的に自分自身を参照する場合
module.exports.function名()
で参照できる
module.exports.readdirRecursively = (dir, files = []) => {
const dirents = fs.readdirSync(dir, { withFileTypes: true });
const dirs = [];
for (const dirent of dirents) {
if (dirent.isDirectory()) dirs.push(`${dir}/${dirent.name}`);
if (dirent.isFile()) files.push(`${dir}/${dirent.name}`);
}
for (const d of dirs) {
// 参考:https://qiita.com/potyosh/items/b37a172219d16ce09435
files = module.exports.readdirRecursively(d, files);
}
return files;
}
node.jsでexportsした関数を定義したファイルから呼び出す - Qiita
メインプロセスとレンダラープロセスの通信
render_process.js// レンダラープロセスでやりとりするipcRenderer const {ipcRenderer} = require('electron'); // synchronous-messageチャンネルで文字列"ping"を同期通信で送信、戻り値を取得 var ret = ipcRenderer.sendSync('synchronous-message', 'ping'); // 戻り値"pong"が出力される console.log(ret);
main_process.js// メインプロセスでやりとりするipcMain const {ipcMain} = require('electron'); //synchronous-messageチャンネルの受信処理 ipcMain.on('synchronous-message', (event, arg) => { // "ping"が出力される console.log(arg) // 呼び出し元の戻り値に文字列"pong"を設定 event.returnValue = 'pong' })
【Electron連載】第4回 基本編-メイン/レンダラープロセスの話 - Qiita
ipcRenderer | Electron
ipcMain | Electron