Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in php, get value in node js

I have a js file running in node. This js file reads data coming 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?

like image 491
Megool Avatar asked Jul 08 '26 07:07

Megool


1 Answers

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.

like image 108
David Zorychta Avatar answered Jul 10 '26 21:07

David Zorychta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!