1
0

More than 3 years have passed since last update.

2020.11.03~ Node.jsで調べたこと

Posted at

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 Documentation

const path = require('path');
let absolutePath = path.resolve('./test.txt');
// => /Users/.../test.txt (絶対パス)

[NodeJS]相対パスを絶対パスに変換する方法 | YongJin Kim's Blog

共通処理を別ファイルでモジュール化

module.exports.add = function (v1, v2) {
    return v1 + v2;  
};
module.exports.minus = function (v1, v2) {
    return v1 - v2;  
};

[NodeJS] モジュール定義について学ぶ - YoheiM .NET

共通処理内で再帰的に自分自身を参照する場合

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

1
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
1
0