最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - in php, get value in node js - Stack Overflow

programmeradmin3浏览0评论

I have a js file running in node. This js file reads data ing from a bluetooth device. I also have a php file that is running in apache server. This displays a website interface.

Now, in the php file, I want to use the data from the js file. What are the possible methods to achieve this?

I have a js file running in node. This js file reads data ing from a bluetooth device. I also have a php file that is running in apache server. This displays a website interface.

Now, in the php file, I want to use the data from the js file. What are the possible methods to achieve this?

Share Improve this question asked Apr 20, 2015 at 3:36 MegoolMegool 9992 gold badges8 silver badges31 bronze badges 4
  • 3 The best would be to also serve the UI with Node... Second best, fill a database from Node, show the database from PHP. – Amadan Commented Apr 20, 2015 at 3:39
  • Third option create an internal API for yourself so node can municate with Apache – scrowler Commented Apr 20, 2015 at 3:46
  • would something like express work? – Megool Commented Apr 20, 2015 at 3:57
  • 1 Yes, express fits very well into the #1 strategy above (have Node serve everything). – Amadan Commented Apr 20, 2015 at 3:59
Add a ment  | 

1 Answer 1

Reset to default 7

An incredibly simple way to do this would be for your node application to act as a web server and for your PHP application to do HTTP requests to your node web server. In Node:

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

Now from PHP you can retrieve this data using:

<?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

?>

Another solution would be to use a message passing system. This would essentially be a queue where in node you would enqueue data as it became available via bluetooth, and you would dequeue data from PHP whenever possible. This solution would be a little more involved but is tremendously more flexible/scalable to what your needs might be, and there are many cross language message passing applications such as RabbitMQ.

发布评论

评论列表(0)

  1. 暂无评论