Help us understand the problem. What is going on with this article?

Node.jsからPHPのプロセスを呼び出す - JSONでやりとり編

More than 5 years have passed since last update.

node.js側の実装

Node.jsのAPIだけでやってます。
PHPをコマンドラインで呼び出します。

icallyou.js
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);
});

PHP側の実装

php://stdinで標準入力を取得できます。

callme.php
<?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);
}

実行してみる

$ node icallyou.js 
stdout:  { status: 'success', message: 'OKです' }
stdout:  { status: 'error',
  message: 'フォーマットに誤りがあります。JSONの配列で送ってこいゴルァ' }
phpプロセスが終了しました: ステータスコード: 0
php2プロセスが終了しました: ステータスコード: 1
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした