2017-05-06 226 views
2

我想實現iOS推送通知。我的PHP版本停止工作,我一直無法再次工作。但是,我有一個完美的node.js腳本,使用Apple的新Auth Key。我可以從PHP使用這樣的呼叫:如何從PHP exec()調用Node.js腳本時傳遞參數?

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) 
}); 

回答

3

可以傳遞參數,你會它傳遞給任何其他腳本。

node index.js param1 param2 paramN 

可以通過process.argv

的process.argv屬性返回包含在命令行參數 當Node.js的過程發起傳遞數組訪問這些參數。第一個 元素將是process.execPath。如果需要訪問argv [0]的 原始值,請參閱process.argv0。第二個元素將是正在執行的JavaScript文件的 路徑。其餘元素 將是任何其他命令行參數。

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 
+0

它的偉大工程!謝謝! – Lastmboy

+0

@Lastmboy不客氣 –

相關問題