Run PHP Scripts from Node JS

The Problem

Due to the asynchronous only design of ImageMagick within Node JS, I ran into a nightmare trying trying to code a recent web application.  You can not run ImageMagick synchronously in NodeJS, I wasn’t able to get callbacks to work correctly, the npm async series method wasn’t working, and the nesting of ImageMagick functions wasn’t favorable.  Much of my code was using ImageMagick to check the properties of the image and do conditional functions based on the results.

All that complaining said, the bigger frustration is that I already had most of this script written in PHP.  In PHP the script uses an object oriented approach which does allow for a synchronous flow and conditional checks.  So could I use this PHP script along side of my Node JS application?

How to call PHP from Node JS
If you are struggling with the asynchronous nature of Node JS and need to make a synchronous function call that PHP might be better suited for, you can simply utilize both languages. Make a call to a PHP script from Node JS with the exec command.

A bit of digging and all of the solutions I was able to find suggested running Apache along side of Node JS, which would then allow you to call PHP via Apache.  But seriously, this makes no sense.  Calling a web server from a web server on the same machine?  Even worse, I wanted my Node JS web app to be called on port 80, so installing Apache will create a port conflict, etc.

I want to give credit to for being the only reference I could find on how to beautifully blend Node JS with the synchronous methods of ImageMagick in PHP.

The Solution

Setup a Child Process Dependency

Call PHP via Child Process Dependency

Using the Node JS exec command, we can call to a PHP script.

The exec command is essentially just calling a linux command directly.  So the first part of the command, php, invokes the PHP application.  We then tell it what the path is to the PHP script, and lastly provide any arguments we want to pass to PHP.  In my case I wanted to pass multiple values, so I comma separated them.

The exec command will return any errors thrown, the output of the PHP script, and any additional errors.

In your PHP script, the argument you pass (argsString) will be available in the $argv array at position 1.  Split that string on it’s delimiter, a comma in my example, and you have an array of the values you passed to PHP.  Any echo calls will be returned to the output (phpResponse) to Node JS.

Node JS Script:



PHP Script: