node.js node.jsスクリプトをforeverでデーモン化する

Javascript

node.jsスクリプトをデーモン化するツールにforeverというものがあります。
https://github.com/nodejitsu/forever

foreverは起動したnode.jsスクリプトの死活監視を行い、停止した場合は自動的に再起動します。

mmonit/Upstart/daemontools等、同様な機能を持つツールと比較しと、node.jsとの親和性が高くお手軽なことがメリットです。また、node.jsスクリプトからインスタンスを生成して操作することが可能です。

以下Version 0.7.2で確認した内容になります。

インストール

 npm install forever -g

※プログラムから利用する場合はローカルインストールしたほうが良いです。

 cd /path/to/project
 npm install forever

主なオプションは下記の通りです。

node.jsスクリプトの起動

 forever start app.js

実行中スクリプトの表示

 forever list

実行中スクリプトの停止や再起動

 forever stop
 forever stopall
 forever restart

引数

forever -hでヘルプが表示されます

 forever [action] [options] SCRIPT [script-options]

アクション

    start               Start SCRIPT as a daemon
    stop                Stop the daemon SCRIPT
    stopall             Stop all running forever scripts
    restart             Restart the daemon SCRIPT
    list                List all running forever scripts
    config              Lists all forever user configuration
    set <key> <val>     Sets the specified forever config <key>
    clear <key>         Clears the specified forever config <key>
    logs                Lists log files for all forever processes
    logs <script|index> Tails the logs for <script|index>
    columns add <col>   Adds the specified column to the output in `forever list`
    columns rm <col>    Removed the specified column from the output in `forever list`
    columns set <cols>  Set all columns for the output in `forever list`
    cleanlogs           [CAREFUL] Deletes all historical forever log files

オプション

    -m  MAX          Only run the specified script MAX times スクリプトの起動回数制限 
    -l  LOGFILE      Logs the forever output to LOGFILE foevert本体のログ
    -o  OUTFILE      Logs stdout from child script to OUTFILE 子スクリプト標準出力のログ 
    -e  ERRFILE      Logs stderr from child script to ERRFILE 子スクリプト標準エラー出力のログ 
    -p  PATH         Base path for all forever related files (pid files, etc.)
    -c  COMMAND      COMMAND to execute (defaults to node) 実行するコマンド(デフォルトはnode)
    -a, --append     Append logs ログを追記する 
    --pidfile        The pid file
    --sourceDir      The source directory for which SCRIPT is relative to
    --minUptime      Minimum uptime (millis) for a script to not be considered "spinning" 最低使用時間(ミリ秒)
    --spinSleepTime  Time to wait (millis) between launches of a spinning script. 実行中スクリプトの起動待ち時間
    --plain          Disable command line colors
    -d, --debug      Forces forever to log debug output
    -v, --verbose    Turns on the verbose messages from Forever
    -s, --silent     stdout/stderrへの出力を抑制する Run the child script silencing stdout and stderr
    -w, --watch      Watch for file changes ファイル変更を監視する 
    -h, --help       You're staring at it

node.jsアプリからforeverインスタンスを操作する

node.jsスクリプト内からforeverモジュールを使うことができます。

   var forever = require('forever');
 
   var child = new (forever.Monitor)('your-filename.js', {
     max: 3,
     silent: true,
     options: []
   });
  child.on('exit', this.callback);
  child.start();

node.js以外のプログラムをデーモン化する

node.jsスクリプトからperlワンライナーをデーモン化する例です。

 var forever = require('forever');
 var child = forever.start([ 'perl', '-le', 'print "moo"' ], {
   max : 1,
   silent : true
 });

サーバー起動時に自動的にforeverを自動開始する

/etc/rc.localに記述するのが簡単です。
/etc/rc.localの記述例です。

 /usr/local/bin/node /usr/local/bin/forever start \
   -p /var/run/forever \
   --pidfile /var/run/node-app.pid \
   -l /var/log/node-app.log -a \
   -d /home/node/ \
   /home/node/app.js

node.js expressのスケルトンコードでエラーCannot find module ‘jade’が発生する

Javascript

node.jsのexpressで自動生成されたスケルトンコードを実行すると下記のようなエラーが発生しました。

 Express
 500 Error: Cannot find module 'jade'
 at Function.Module._resolveFilename (module.js:338:15)
 at Function.Module._load (module.js:280:25)
 at Module.require (module.js:364:17)
 at require (module.js:380:17)
 at new View (.../node_modules/express/lib/view.js:43:49)
 at Function.app.render (.../node_modules/express/lib/application.js:486:12)
 at ServerResponse.res.render (.../node_modules/express/lib/response.js:801:7)
 at exports.index (.../routes/index.js:7:7)
 at callbacks (.../node_modules/express/lib/router/index.js:164:37) 
 at param (.../node_modules/express/lib/router/index.js:138:11)

jadeモジュールがapp.js以下にインストールされていないことが原因です。
app.jsがあるディレクリで下記コマンドを実行すると正常に実行できるようになります。

 npm install -d

node.js Windowsでの開発の仕方

Node.js MySQLに接続して結果を表示するサンプルコード
node.js
Javascript

Node.jsをWindows上で開発するのはとっても簡単です!

下記から
https://nodejs.org/ja/

推奨版をダウンロードして実行するだけです(笑)
これを書いている現在(2017/03/31)時点で、6.10.1LTSが推奨版です。

インストールできたかどうかは、コマンドプロンプトから、node -h とでもやってみましょう。

node-js-help.png

node.js TypeError

Javascript
node.js

node.js TypeError: first argument must be a string or Buffer

かなりメモ的な話なのですが、node.jsをアップグレードしたらこのようなエラーが出るようになりました。

 response.write(JSON.parse(JSON.stringify(data)));  

としていたところを

 response.write(JSON.stringify(data));  

としたら治りました!

node.js Hello Worldを表示させる

Javascript

node.js Hello Worldを表示させる

node.js version 0.2.2

node.js インストール]]で[[node.jsをWebサーバーにインストールし終わったら、次はHello Worldを表示させてみます。

次のようなスクリプトを書いて、example.jsという名前でWebサーバーに保存します。
内容は、8124番のポートでこのWebサーバーに接続すると、「Hello World」が表示される、というものです。

 var http = require('http');
 
 http.createServer(function (request, response) {
   response.writeHead(200, {'Content-Type': 'text/plain'});
   response.end('Hello World\n');
 }).listen(8124);
  
 console.log('Server running at http://127.0.0.1:8124/');

サーバー上で、このexample.jsをnodeというコマンドで実行します。

 # node example.js
 Server running at http://127.0.0.1:8124/

と表示されたでしょうか?
されていれば、動作しています。

これで、このWebサーバーのどこに接続しても、ポート番号8124で接続すれば、「Hello World」と表示されるかと思います。

 http://Webサーバーのアドレス:8124/以下任意のパス

Webシステム開発のご依頼はこちら