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

标签 javascript php ios node.js apple-push-notifications

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

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

但是,我希望能够将 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)
});

最佳答案

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

node index.js param1 param2 paramN

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

The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched. The first element will be process.execPath. See process.argv0 if access to the original value of argv[0] is needed. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command line arguments.

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为您解析参数:

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

关于javascript - 从 PHP exec() 调用 Node.js 脚本时如何传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43825359/

相关文章:

javascript - 如何在 Angular 中获取动态渲染元素的尺寸

javascript - ExtJS 将多个 vType 应用于一个字段

php - 如何编写正则表达式来匹配 ftp、ftps 或 sftp?

php - 已弃用 : strpos(): Non-string needles will be interpreted as strings in the future

ios - 如何更新核心数据中的对象?

iPhone iOS如何按需重绘UINavigationBar?

iphone - [UIViewController disablesAutomaticKeyboardDismissal] 什么时候被调用?

javascript - 如何解构云函数参数?

javascript - 将字符串拆分为单词数组以查找最长的

php - 当满足所有条件时防止重复的 MYSQL 条目