【问题标题】:How can I pass parameters when calling a Node.js script from PHP exec()?从 PHP exec() 调用 Node.js 脚本时如何传递参数?
【发布时间】:2017-10-05 03:22:19
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    经过大量工作,我有一个解决方案。我正在使用本地 Web UI 向/从 Arduino 发送和接收数据 使用 AJAX,php 脚本为:

     <?php
      /**
      * Remember to go to Device Manager> Ports (COM & LPT)>Arduino XXX (COMXX)>right
      * click>Properties>
      * Port Settings>Advanced>uncheck "use FIFO buffers ........."
      * In other hand, remeber that the Tx speed has to be the same in writeandread.js as in
      * Arduino sketch and in the COM
      * properties in Device manager, I selected 115200 b/s.
      *
      */
      $puerto = escapeshellarg("COM3");
      $dato = escapeshellarg("<4,2,20>");
      exec("node C:/xampp/htdocs/DisenoWEBTerminados/BatteryTester/Scripts/writeandread.js {$puerto} {$dato} 2>&1", $output);
      $myJSON = $output;
      $pepe = implode($myJSON);
      echo $pepe;
      echo "<script>console.log('Rx from Arduino ".$pepe."')</script>";
    
      ?>
    

    Node Js 脚本是:

    var portName = process.argv[2];
    var dato = process.argv[3];
    
    var SerialPort = require("serialport");
    var Readline = require('@serialport/parser-readline');
    var serialport = new SerialPort(portName, { baudRate: 115200 });
       // Look for return and newline at the end of each data packet
    var parser = serialport.pipe(new Readline({ delimiter: '\n' }));
    
    serialport.on('open', function(err) {
        // A timeout is necessary to wait the port to open (if not working, try to 
       increase the milliseconds value)
        setTimeout(function() {
            serialport.write(dato);
        }, 1700);
        if(err) {
            console.log('Error when trying to open:' + err);
        }
        parser.on('data', function(data) {
            console.log(data);
            serialport.close(function (err) {
               if(err){
                    console.log('port closed', err);
                }
             });
         });
     });
    
    serialport.on('close', () => {
     console.log('Bye');
    });
    

    使用此脚本,您可以从 Arduino 发送和接收数据,并将其传递给客户端的 AJAX 脚本,然后做自己想做的事。现在我在 php 中添加一个脚本,以编程方式检测 Arduino 连接到的 COM 端口。

    享受吧。

    【讨论】:

      【解决方案2】:

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

      node index.js param1 param2 paramN
      

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

      process.argv 属性返回一个包含命令行的数组 启动 Node.js 进程时传递的参数。首先 元素将是 process.execPath。如果访问,请参见 process.argv0 需要 argv[0] 的原始值。第二个元素将是 正在执行的 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
      

      【讨论】:

        猜你喜欢
        • 2020-11-24
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-21
        • 2011-10-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多