从PHP exec()调用Node.js脚本时如何传递参数?

Las*_*boy 7 javascript php apple-push-notifications node.js ios

我正在尝试实现iOS推送通知.我的PHP版本停止工作,我无法让它再次运行.但是,我有一个使用Apple的新Auth Key完美运行的node.js脚本.我可以使用以下方法从PHP调用它:

chdir("../apns");
exec("node app.js &", $output);
Run Code Online (Sandbox Code Playgroud)

但是,我希望能够将deviceToken和消息传递给它.有没有办法将参数传递给脚本?

这是我正在尝试运行的脚本(app.js):

var apn = require('apn');

var apnProvider = new apn.Provider({  
     token: {
        key: 'apns.p8', // Path to the key p8 file
        keyId: '<my key id>', // The Key ID of the p8 file (available at https://developer.apple.com/account/ios/certificate/key)
        teamId: '<my team id>', // The Team ID of your Apple Developer Account (available at https://developer.apple.com/account/#/membership/)
    },
    production: false // Set to true if sending a notification to a production iOS app
});

var deviceToken = '<my device token>';
var notification = new apn.Notification();
notification.topic = '<my app>';
notification.expiry = Math.floor(Date.now() / 1000) + 3600;
notification.badge = 3;
notification.sound = 'ping.aiff';
notification.alert = 'This is a test notification \u270C';
notification.payload = {id: 123};

apnProvider.send(notification, deviceToken).then(function(result) {  
    console.log(result);
    process.exit(0)
});
Run Code Online (Sandbox Code Playgroud)

Mar*_*nde 13

您可以传递参数,就像将其传递给任何其他脚本一样.

node index.js param1 param2 paramN
Run Code Online (Sandbox Code Playgroud)

您可以通过process.argv访问参数

process.argv属性返回一个数组,其中包含启动Node.js进程时传递的命令行参数.第一个元素是process.execPath.如果需要访问argv [0]的原始值,请参阅process.argv0.第二个元素将是正在执行的JavaScript文件的路径.其余元素将是任何其他命令行参数.

exec("node app.js --token=my-token --mesage=\"my message\" &", $output);
Run Code Online (Sandbox Code Playgroud)

app.js

console.log(process.argv);

/* 
Output:

[ '/usr/local/bin/node',
  '/your/path/app.js',
  '--token=my-token',
  '--mesage=my message' ] 
*/
Run Code Online (Sandbox Code Playgroud)

您可以使用minimist为您解析参数:

const argv = require('minimist')(process.argv.slice(2));
console.log(argv);

/*
 Output

{
    _: [],
    token: 'my-token',
    mesage: 'my message'
} 
*/

console.log(argv.token) //my-token
console.log(argv.message) //my-message
Run Code Online (Sandbox Code Playgroud)