iOS: Building complex Node.js projects

This guide will show you how to start the node runtime from a project folder on iOS. It builds on top of the iOS Getting Started instructions, having the same functionality but using a nodejs-project folder that contais the node part of the project. It also shows how to use an npm module in the project.

The complete project can also be downloaded from the samples repo.

Create the nodejs-project folder

Create a nodejs-project folder inside the project and add it as a Resource to the Xcode project. It contains two files inside:

  • main.js
var http = require('http');
var versions_server = http.createServer( (request, response) => {
  response.end('Versions: ' + JSON.stringify(process.versions));
  • package.json
  "name": "native-xcode-node-project",
  "version": "0.0.1",
  "description": "node part of the project",
  "main": "main.js",
  "author": "janeasystems",
  "license": ""

Add a npm module to the nodejs-project

Having a nodejs-project path with a package.json inside is helpful for using npm modules, by running npm install {module_name} inside nodejs-project so that the modules are also packaged with the application and made available at runtime.

Install the left-pad module, by running npm install left-pad inside the nodejs-project folder.

Update main.js to use the module:

var http = require('http');
var leftPad = require('left-pad');
var versions_server = http.createServer( (request, response) => {
  response.end('Versions: ' + JSON.stringify(process.versions) + ' left-pad: ' + leftPad(42, 5, '0'));

Start the node runtime from the Node Project

Change the code that starts the node runtime in AppDelegate.m to find the main.js inside the Application's bundle and start from there:

- (void)startNode {
    NSString* srcPath = [[NSBundle mainBundle] pathForResource:@"nodejs-project/main.js" ofType:@""];
    NSArray* nodeArguments = [NSArray arrayWithObjects:
    [NodeRunner startEngineWithArguments:nodeArguments];