LoginSignup
12
13

More than 5 years have passed since last update.

Node.jsでデスクトップ通知(gulpもね)

Posted at

gulpでdeploy作業を行なっているのですが、処理に時間がかかるので、なんか通知みたいなのできないかなと思い、調べてみると良いモジュールがあったのでそのメモ。

node-notifier

node-notifierを使うとNode.jsでデスクトップ通知ができるようです。
https://github.com/mikaelbr/node-notifier
さっそくインストールしてみます。

$npm install --save-dev node-notifier

package.jsonに追加されます。

package.json
"devDependencies": {
  "node-notifier": "5.3.0",
}

node-notifierを使用する

使用するときは以下のように使います。

const notifier = require('node-notifier');
notifier.notify({
  title: 'タイトル',
  message: 'メッセージ',
});

アイコンやサウンドも設定できるようです。

const notifier = require('node-notifier');
const path = require('path');
notifier.notify({
  title: 'タイトル',
  message: 'メッセージ',
  icon: path.join(__dirname, '/images/hogehoge.png'), // 画像
  sound: 'Funk', // Basso, Blow, Bottle, Frog, Funk, Glass, Hero, Morse, Ping, Pop, Purr, Sosumi, Submarine, Tinkから選択
                 // trueだとデフォルトのBottle
});

他にも色々オプションがあるようです。

gulpと組み合わせる

gulpで完了したときとエラー発生したときに通知送りたいなと思いまして、組み合わせてみました。

成功時の通知

まずはタスクが成功したときの処理。
そのままでは使えないっぽいので、gulp-notifyを使用します。

$npm install --save-dev gulp-notify

gulp-notifyがインストールされました。

package.json
"devDependencies": {
  "gulp-notify": "^3.2.0",
}

成功したときの通知はタスクの最後にpipeで繋げることにします。

gulpfile.js
const gulp = require("gulp");
const gulpnotify = require('gulp-notify');
const path = require('path');

gulp.task('deploy', (cb) => {
  gulp.src(['src/**'], { base: '.' })
    // 本処理
    .pipe(hogehoge())
    // 処理の最後に通知する
    .pipe(gulpnotify({
        title: 'deploy完了しました',
        icon: path.join(__dirname, '/images/hogehoge.png'),
        sound: 'Funk',
    }));
});

これで処理が完了した時に通知されるようになりました。

失敗時の通知

失敗したときは通知はgulp-plumberと組み合わせます。
gulp-plumberを使用すればgulpのエラーハンドリングができます。

$npm install --save-dev gulp-plumber
package.json
"devDependencies": {
  "gulp-plumber": "^1.2.1",
}

エラー処理を記述し、gulp-plumberでエラー時に実行させます。

gulpfile.js
const gulp = require("gulp");
const gulpnotify = require('gulp-notify');
const path = require('path');
const plumber = require("gulp-plumber");

gulp.task('deploy', (cb) => {
  gulp.src(['src/**'], { base: '.' })
    // gulp-plumberでエラーハンドリング
    .pipe(plumber({errorHandler: (error) => { // エラー処理
      // エラー処理を記述
      hogehogeError();
      // エラー通知
      notifier.notify({
        title: '実行エラー',
        message: error.message,
        icon: path.join(__dirname, '/images/hogehoge.png'),
        sound: 'Funk',
      });
      cb(error);
    }}))
    // 本処理
    .pipe(hogehoge())
    // 処理の最後に通知する
    .pipe(gulpnotify({
        title: 'deploy完了しました',
        icon: path.join(__dirname, '/images/hogehoge.png'),
        sound: 'Funk',
    }));
});

これでエラー時にも通知が届くようになり、deploy中に他の作業が気兼ねなくできるようになりました!

12
13
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
12
13