posted this on November 01, 2011 17:27
In this article, we'll walk you through the creation of a simple Hello World program. If you followed our last two lessons, you already have a Cloud9 IDE account and you know how to create a project. To get started with Lesson 3, you'll need to first create a (Github or Mercurial) project. If you need a refresher on how to do this, please refer to Lesson 2.
A Simple Node.js HTTP Server
Once you have created your project, click on the Start Editing button to go to the Cloud9 IDE editor. In the editor, create a new file called server.js. Type the following code in the file:
What you just wrote is a Node.js HTTP server that returns a simple 'Hello World' page for every request. In short, you are creating an HTTP server with a callback function that is called for each request. In the callback function, you create a response with a status code of 200 (indicating that the request was fulfilled successfully) and the message "Hello World". Finally, you specify which port the server listens to. When Node.js projects run within Cloud 9 IDE, you can retrieve the port information with process.env.PORT
Running your program
With Cloud9 IDE, you can run your Node.js applications in a test environment and see the results of your coding. Before running your "Hello, World" application, make sure that your server.js file is open in the editor. Cloud9 will run whichever file is the active file in the project. To confirm that server.js is the active file, go to the Run Panel by clicking on Run in the Project Bar (left side of the editor). You should see the following:
You can also instruct Cloud9 to always run the same file with certain parameter by creating a Run configuration. To create a run configuration, click on add at the top of the Run Panel.
Once server.js appears as the active file in the Run Panel, click on the run button in the menu bar. The run button will turn into a stop button. Your application will be deployed to one of our servers, and you will immediately see some output similar to the one below:
To see your application in action, click on the link created for your project. You should see your "Hello World" application open up in a new browser tab:
To stop your application, go back to the editor and click on the stop button.
Congratulations! You have just written and run a node.js application in Cloud 9 IDE!