Write command line scripts for Node.js using ActionScript
Create a file named MyServer.as, and add the following code:
package { public class MyServer { public function MyServer() { } } }
Apache Royale requires an ActionScript class, like this one, as the entrypoint for a Node.js project. The constructor will run automatically on startup.
Next, let's expand this code to create a simple server using the “http” module provided by Node.js.
package { import http.IncomingMessage; import http.Server; import http.ServerResponse; public class MyServer { private static const HOSTNAME:String = "localhost"; private static const PORT:int = 3000; public function MyServer() { var server:Server = http.createServer(handleRequest); server.listen(PORT, HOSTNAME, handleServerStart); } private function handleRequest(req:IncomingMessage, res:ServerResponse):void { res.statusCode = 200; res.setHeader("Content-Type", "text/plain"); res.end("Hello World\n"); } private function handleServerStart():void { console.log("Server running at http://" + HOSTNAME + ":" + PORT + "/"); } } }
Notice that there's no need to call
require("http")
, as would be necessary in plain JavaScript. When the Apache Royale compiler detects a reference to a Node.js module, likehttp
, it automatically generates the appropriaterequire()
calls.
Using Apache Royale's asnodec compiler, compile our project into JavaScript that can be run with Node.js:
asnodec src/MyServer.as
The generated JavaScript code will be created in the bin/js-debug folder for debug builds, and the bin/js-release folder for release builds.
Use the following command to run the compiled project:
node bin/js-release/index.js
In a web browser, open http://localhost:3000/ and verify that you can see a webpage that simply contains the text, “Hello World”.