Created
January 25, 2012 13:10
-
-
Save suin/1676186 to your computer and use it in GitHub Desktop.
Node.jsからPHPのプロセスを呼び出す - JSONでやりとり編 ref: http://qiita.com/items/1879
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$stdin = file_get_contents('php://stdin'); | |
$data = json_decode($stdin, true); | |
// var_dump($data); | |
if ( is_array($data) === false ) | |
{ | |
echo json_encode(array( | |
'status' => 'error', | |
'message' => 'フォーマットに誤りがあります。JSONの配列で送ってこいゴルァ', | |
)); | |
exit(1); | |
} | |
else | |
{ | |
echo json_encode(array( | |
'status' => 'success', | |
'message' => 'OKです', | |
)); | |
exit(0); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ node icallyou.js | |
stdout: { status: 'success', message: 'OKです' } | |
stdout: { status: 'error', | |
message: 'フォーマットに誤りがあります。JSONの配列で送ってこいゴルァ' } | |
phpプロセスが終了しました: ステータスコード: 0 | |
php2プロセスが終了しました: ステータスコード: 1 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var util = require('util'); | |
var spawn = require('child_process').spawn; | |
var php = spawn('php', ['callme.php']); // $ php callme.php と同じ意味 | |
var data = { | |
'foo': 'something', | |
'bar': 'something', | |
}; | |
php.stdin.write(JSON.stringify(data)); // 標準入力としてPHPに渡す | |
php.stdin.end(); // PHPさん、標準入力終わったよ | |
php.stdout.on('data', function (data) { | |
console.log('stdout: ', JSON.parse(data)); | |
}); | |
php.stderr.on('data', function (data) { | |
console.log('stderr: ', JSON.parse(data)); | |
}); | |
php.on('exit', function (code) { | |
console.log('phpプロセスが終了しました: ステータスコード: ' + code); | |
}); | |
// ↓エラーなパターン | |
var php2 = spawn('php', ['callme.php']); | |
var data = 'なんか変なデータ'; | |
php2.stdin.write(JSON.stringify(data)); | |
php2.stdin.end(); | |
php2.stdout.on('data', function (data) { | |
console.log('stdout: ', JSON.parse(data)); | |
}); | |
php2.stderr.on('data', function (data) { | |
console.log('stderr: ', JSON.parse(data)); | |
}); | |
php2.on('exit', function (code) { | |
console.log('php2プロセスが終了しました: ステータスコード: ' + code); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment