by Josh Tynjala
Over the years, many developers have dreamed of using ActionScript on both the client and the server. Today, transpilers make it possible.
Previously, we learned how to transpile ActionScript for the web browser using Apache FlexJS™. The transpiler also enables ActionScript developers to write code that runs in the popular server-side JavaScript environment, Node.js.
The asnodec
transpiler gives you full access to all Node.js APIs, and it's even possible to require NPM modules in ActionScript. Let's get started with a simple example.
For this tutorial, you should install Apache FlexJS 0.7 or newer. Use the Apache Flex SDK Installer to download it.
Create a new folder for your project, and name it HelloNode
.
Inside the new project, create a new folder named src
. This is where our ActionScript classes will go.
Inside the src
folder, create a file named HelloNode.as
, and add the following code:
package
{
public class HelloNode
{
public function HelloNode()
{
dns.lookup("localhost", null, dnsLookupCallback);
}
private function dnsLookupCallback(error:Object, address:String):void
{
console.log("The address of localhost is:", address);
}
}
}
In this class, we're using Node's built-in dns
module to look up an IP address.
require()
for Node modules in ActionScript. The compiler will detect when a module is used, and it will generate the appropriate call to require()
automatically when transpiling to JavaScript.
Inside Apache FlexJS, the js/bin
folder contains the ActionScript to JavaScript transpilers. Use the asnodec
executable from this folder to transpile the HelloNode
ActionScript class that you created above for Node.js.
asnodec src/HelloNode.as
This will produce a folder named bin
containing js-debug
and js-release
folders. The js-debug
folder contains JavaScript that is easy to read, and each class is loaded at runtime from a separate file. The js-release
folder contains JavaScript that has been concatenated and minified.
The project should now contain the following files and folders:
Finally, let's try running our code with Node.js.
Inside the js-debug
folder, a file named index.js
will be created as the entry point for your Node.js project. You can run this script using the node
executable:
node bin/js-debug/index.js
You should see the following output in your console:
The address of localhost is: 127.0.0.1
This is just a simple example, but it gives you a glimpse of how developers can bring ActionScript server-side using Apache FlexJS and Node.js. By using an established ecosystem like Node.js, ActionScript developers can take advantage of all of the libraries published to NPM and join a large, vibrant community.
Would you like to learn more about transpiling ActionScript? Please become a patron, and support the creation of a whole library of detailed, step-by-step tutorials — including video tutorials! Let's work together to teach the next generation of ActionScript developers.