Access to Wordpress from Node.js

First we will need access to a Wordpress (obviously).

Let’s start a project with Express.

If you don’t have express-generator you can install with:

npm install express-generator -g

Create a new dir for the project:

mkdir node-wordpress
cd node-wordpress

Starting express generator with “hbs” (handlebars template engine) option:

express --hbs

Add node-wordpress library:

npm i --save wordpress

Install all dependences:

npm i

Start the project:

DEBUG=node-wordpress:* npm start

This is a sample of routes/index.js

var express = require('express');
var router = express.Router();

var wordpress = require( "wordpress" );
var client = wordpress.createClient({
    url: "http://mywwordpresssite.com",
    username: "myuser",
    password: "mypassword"
});


/* GET home page. */
router.get('/', function(req, res, next) {
  client.getPosts({ status: 'publish' }, function( err, posts ) {
		if (err) {
		   next(err);
		} else {
		   
		   for (var i = 0, len = posts.length; i < len; i++) {
		      console.log('title: '+posts[i].title);
		      console.log('status: '+posts[i].status);
		      console.log('-----------------------------------');
		    }
		   
	       res.render('index', { title: 'Express', posts: posts });
	    }
  });
  
});

module.exports = router;

And this is the hbs file /views/index.hbs

<h1></h1>

<h1></h1>
<p>

What is fastest? HTML, Lua, Node.js, or PHP

I installed in a server OpenResty and PHP-FPM.

OpenResty is very interesting because Lua is integrated with Nginx.

This is Nginx configuration for Lua:

location /lua {
        default_type text/html;
        content_by_lua 'ngx.say("<p>Hello</p>")';
}

And for PHP-FPM:

location ~ \.php$ {
            fastcgi_pass   unix:/var/run/php5-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

This is a little program with Express:

var express = require('express');
var app = express();
app.get('/', function (req, res) {
  res.send('<p>Hello</p>');
});
var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});

I used Apache HTTP server benchmarking tool for tests:

ab -k -n 50000 -c 2 -e lua.csv http://192.168.0.55/lua
ab -k -n 50000 -c 2 -e html.csv http://192.168.0.55/index.html
ab -k -n 50000 -c 2 -e node.csv http://192.168.0.55:3000
ab -k -n 50000 -c 2 -e php.csv http://192.168.0.55/index.php

All pages show same content:

<p>Hello</p>

And these are the results:

fastest_lua_graph_00

fastest_lua_graph_01

And the winner is Lua!!!

}</p>

Go to http://localhost:3000 and see the result.

More information about handelbars template engine here.

Next week I’m going to write about how to use Memcached to improve this project.