Node.js 通过 child_process 模块的 exec 或 spawn 启动 PHP 进程执行脚本;exec 适合短时小输出,spawn 更适合长时间、大输出或需实时交互的场景,二者均需确保 php 可执行路径正确、脚本有读取权限且参数安全传递。
PHP 脚本怎么被 Node.js 调用(不是“piso”,应为 exec 或 spawn)
Node.js 本身不能直接调用 PHP 函数,但可以通过 child_process 模块启动外部进程执行 PHP 脚本。所谓“piso”很可能是输入错误或混淆了命令名——实际要用的是 exec、spawn 或 execFile。
用 exec 运行 PHP 脚本的典型写法
exec 适合运行短时、输出量不大的脚本,它会等脚本结束再返回结果。常见错误是忽略 PHP 可执行路径或脚本路径错误。
示例:
const { exec } = require('child_process');
exec('php /path/to/script.php arg1 arg2', (error, stdout, stderr) => {
if (error) {
console.error('PHP 执行失败:', error.message);
return;
}
if (stderr) console.error('PHP stderr:', stderr);
console.log('PHP 输出:', stdout.trim());
});
- 确保系统 PATH 中有
php命令,否则改用绝对路径如/usr/bin/php -
script.php需有可读权限,且首行无需#!/usr/bin/env php(exec不依赖 shebang) - 参数带空格或特殊字符时,必须手动 shell 转义,或改用
spawn更安全传参 -
stdout是字符串,大输出可能被截断(maxBuffer默认 1MB)
为什么有时 spawn 比 exec 更合适
当 PHP 脚本运行时间长、输出量大、或需要实时响应(比如进度回调)、或要传二进制参数时,spawn 是更稳的选择。