Chapter 5. HTTP Responses

In previous chapters, a development environment suitable for PHP to Node.js conversion was set up, a Node.js framework for hosting Node.js code converted from PHP pages was written, and the original PHP code was refactored to make it friendlier to PHP to Node.js conversion (in particular, in terms of handling callbacks). With that done, we are ready to copy and paste the PHP code from the .php file into the corresponding .njs file.

At this point, some or all of your .php files will have a corresponding .njs file in the same directory. All the .njs files in your project will have a stub implementation of the page similar to the following Node.js code:

var initreq = require('./initreq.njs');

exports.serve = function(req, res) {
  var pre = {};
  initGET(req, pre, function() {
    initPOST(req, pre, function() {
      initCOOKIE(req, pre, function() {
        initREQUEST(req, pre, function() {
          page(req, res, pre, function() {

function page(req, res, pre, cb) {
  res.writeHead(200, {'Content-Type': 'text/plain'});

The page() function has a stub implementation. We will copy and paste the PHP code from the .php file into the implementation of the page() function soon. But first, let’s examine how HTTP responses are returned in both PHP and Node.js.

An HTTP response is similar to an HTTP request: it can contain multiple HTTP response headers and a single HTTP response body. In actual implementation, the HTTP response headers are separated ...

Get Node.js for PHP Developers now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.