在php中,获取节点js中的值

Yun*_*Han 3 javascript php node.js

我有一个在节点中运行的js文件.这个js文件读取来自蓝牙设备的数据.我还有一个在apache服务器上运行的php文件.这会显示一个网站界面.

现在,在php文件中,我想使用js文件中的数据.有哪些方法可以实现这一目标?

Dav*_*hta 7

一种非常简单的方法是让您的节点应用程序充当Web服务器,并让您的PHP应用程序对您的节点Web服务器执行HTTP请求.在节点中:

function getBluetoothData(callback) {
  // ... do some bluetooth related stuff here and build data
  callback({ someSortOfData: 'fromBluetoothHere' });
}

// require express, a minimalistic web framework for nodejs
var express = require('express');
var app = express();

// create a web path /getdata which will return your BT data as JSON
app.get('/getdata', function (req, res) {
  getBluetoothData(function(data) {
    res.send(data);
  });
});

// makes your node app listen to web requests on port 3000
var server = app.listen(3000);
Run Code Online (Sandbox Code Playgroud)

现在从PHP可以使用以下方法检索此数据:

<?php

  // perform HTTP request to your nodejs server to fetch your data
  $raw_data = file_get_contents('http://nodeIP:3000/getdata');

  // PHP just sees your data as a JSON string, so we'll decode it
  $data = json_decode($raw_data, true);

  // ... do stuff with your data
  echo $data['someSortOfData']; // fromBluetoothHere

?>
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是使用消息传递系统.这实际上是一个队列,在节点中,当数据通过蓝牙变为可用时,您将数据入队,并且您可以尽可能从PHP中将数据出列.这个解决方案可能会涉及更多,但可以根据您的需求提供更大的灵活性和可扩展性,并且有许多跨语言消息传递应用程序,例如RabbitMQ.