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: "",
    username: "myuser",
    password: "mypassword"

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

module.exports = router;

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



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) {
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
ab -k -n 50000 -c 2 -e html.csv
ab -k -n 50000 -c 2 -e node.csv
ab -k -n 50000 -c 2 -e php.csv

All pages show same content:


And these are the results:



And the winner is Lua!!!


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.