Create a Node.js module with Apache Royale

Write modules with ActionScript that can be loaded with require() in Node.js

One of the reasons why the Node.js ecosystem is so vibrant is the massive number of open source modules available to install from the npm registry. Those modules are all deployed as JavaScript, but they can be written in a variety of languages that can compile to JavaScript, including ActionScript.

A simple module

Create a file named and add the following code:

	public function leftPad(input:String, minLength:int, char:String = " "):String
		var result:String = input;
		while(result.length < minLength)
			result = char + result;
		return result;

This function takes an input string, and if its length is less than the specified minimum, additional characters are appended to to beginning until the result meets the length requirement.

Compile with asnodec

Using Apache Royale’s asnodec compiler, compile the project into JavaScript code that can be run with Node.js:

asnodec -targets=JSNodeModule src/

Use the -targets compiler option to specify that the output should be a module instead of a standalone script.

Run the project

To test the module, create a file named script.js in the root folder of your project, and add the following content:

var leftPad = require("./bin/js-release/index.js");
var inputString = "64";
var result = leftPad(inputString, 4, "0");

To run the generated JavaScript, you must have Node.js installed.

Use the following command to run the script:

node script.js

The following output will appear in the console:


Deploy the module

To deploy a module to the npm registry, you must create a package.json file.

For a project compiled with Apache Royale, the main field should point to the generated JavaScript entry point:

	"name": "my-left-pad",
	"version": "1.0.0",
	"main": "bin/js-release/index.js"

When your package is installed in a user’s project, they should call require() using the value of name field in your module’s package.json.

For complete details about publishing a package to the npm registry, please see npm: Packages and modules.