Showing posts with label Cloud9 IDE. Show all posts
Showing posts with label Cloud9 IDE. Show all posts

Thursday, 5 April 2012

Timers in Nods.js


You can use the JavaScript timers, such as setTimeout(), clearTimeout(), setInterval(), clearInterval() in your node apps. All of the timer functions are globals. You do not need to require() this module in order to use them.
To schedule the repeated execution of callback every delay milliseconds you can use the setInterval() method. The setInterval returns an intervalId which can be later used to clear the interval execution with the clearInterval() method.
Similary to schedule execution of a one-time callback after delay milliseconds use the setTimeout() method.
var index = 0;

setTimeout(function (timeoutMessage) {
    console.log(timeoutMessage);
}, 100, 'Hello timeout');

var intervalId = setInterval(function (message) {
    index++;
    if (index == 5) {
        clearInterval(intervalId);
    }
    console.log(message);
}, 200, 'Hello interval');


Wednesday, 4 April 2012

File I/O in Node


The fs module provides both synchronous and asynchronous ways of reading files. The readFile method reads the contents of the file asynchronously.
fs = require('fs');
fs.readFile(file, [encoding], [callback]);

where file is the name of the file to read, encoding is an optional parameter that specifies the type of encoding to read the file. Possible encodings are 'ascii', 'utf8', and 'base64'. If no encoding is provided, the default is utf8.callback is a function to call when the file has been read and the contents are ready - it is passed two arguments, error and data. If there is no error, error will be null and data will contain the file contents; otherwise err contains the error message.
Similarly the writeFile method writes content to a file specified in the function.
var fileSystem = require('fs');

var textToWrite = 'The easiest way to read the entire contents of a file is with fs.readFile, fs.readFile(file, [encoding], [callback]); encoding is an optional parameter that specifies the type of encoding to read the file. Possible encodings are \'ascii\', \'utf8\', and \'base64\'';
textToWrite = textToWrite + '. If no encoding is provided, the default is utf8. callback is a function to call when the file has been read and the contents are ready - it is passed two arguments, error and data. If there is no error, error will be null and data will contain the file contents; otherwise err contains the error message.';

fileSystem.writeFile(__dirname + '/HowToRead.txt', textToWrite, function (error) {
    if (error) {
        console.log('Error writing file!!!' + error);
    }
});

fileSystem.readFile(__dirname + '/SampleText.txt', 'utf8', function (error, data) {
    if (error) {
        console.log('Error reading file!!!' + error);
    }
    console.log(data);
});


Saturday, 31 March 2012

Creating a Node.js program in Cloud9 IDE


Cloud9 IDE is an online development environment for Javascript and Node.js applications as well as HTML, CSS, PHP, Java, Ruby and 23 other languages. Cloud9 IDE lets you build, debug, and run your Node.js applications within the browser. Set breakpoints, follow the call stack, and analyze your performance. In this post I’ll demonstrate how to build a simple Node.js server app using Cloud9 IDE.
Creating a new project:
Creating a project in Cloud 9 IDE requires an account which is available as a free subscription at http://c9.io/. After successful registration you can create a new project by adding a new project form the dashboard.


After entering the project name you can select the type of project to create
·         Git project: will allow you to run git commands from the console and push your changes to Github
·         Mercurial: will allow you to run hg commands form the console and push your changes to Bitbucket.
·         FTP: will allow you to upload your files directly to an FTP server you have access to.
Select create after choosing a project type. Now, just click Start Editing to get started!
You can right click on the selected project and add a ‘New File’

Creating the node.js server
We’ll create a simple http server with controllers to handle the request and send the response to the clients. Create a new loginController.js file and add the code given below.
exports.process = function handle(response) {
    response.writeHead(200);
    response.end('<html>' +
                    '<head>' +
                        '<meta http-equiv="Content-Type" content="text/html; ' +
                        'charset=UTF-8" />' +
                    '</head>' +
                    '<body>' +
                    '<form action="/login" method="post">' +
                         'Login name:<input type=text value="" name="txtLogin" style="width: 100px"></br>' +
                         'Password  :<input type=password value="" name="txtPassword" style="width: 100px"></br>' +
                         '<input type="submit" value="Login" /> &nbsp; &nbsp; <input type="submit" value="Cancel" />' +
                    '</form>' +
                    '</body>' +
                    '</html>');
The process property is assigned to an object called 'exports'. Such an 'exports' object is available in every module, and it is returned whenever the required function is used to include the module. We can now use this function as given below
var loginController = require('./handlers/loginController');
loginController.process(response);
Similarly you can create the other controllers and then the http server like
var http = require('http');
var homeController = require('./handlers/homeController');
var loginController = require('./handlers/loginController');
var errorController = require('./handlers/errorController');
var port = process.env.PORT;

var requestListener = function(request, response)
{
    switch(request.url)
    {
        case '/':
            homeController.process(response);
            break;
        case '/login':
            loginController.process(response);
            break;
        default:
            errorController.process(response);
            break;
    }
}

var server = http.createServer(requestListener);
server.listen(port);
In the first line, we included the http core module and assign it to a variable called http. Later we use this variable called server by calling http.createServer().
You can also 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. You can run the project by clicking the Debug button.