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

我试图实现iOS推送通知。 我的PHP版本停止工作,我还没有能够得到它再次工作。 但是,我有一个完美的node.js脚本,使用苹果的新的身份validation密钥。 我能够从PHP使用:

chdir("../apns"); exec("node app.js &", $output); 

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

下面是我试图运行的脚本(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) }); 

您可以将parameter passing给任何其他脚本。

 node index.js param1 param2 paramN 

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

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

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

app.js

 console.log(process.argv); /* Output: [ '/usr/local/bin/node', '/your/path/app.js', '--token=my-token', '--mesage=my message' ] */ 

您可以使用minimist为您parsing参数:

 const argv = require('minimist')(process.argv.slice(2)); console.dir(argv); /* Output { _: [], token: 'my-token', mesage: 'my message' } */ console.log(argv.token) //my-token console.log(argv.message) //my-message