Node.js for Beginners

Node.js for Beginners

Tutorial Details
    • Program: any text editor (syntax highlighting preferred)
    • Difficulty: very easy
    • Estimated Completion Time: 30-40 minutes

Event-driven programming can be overwhelming for beginners, which can make Node.js difficult to get started with. But don’t let that discourage you; In this article, I will teach you some of the basics of Node.js and explain why it has become so popular.


Introduction

To start using Node.js, you must first understand the differences between Node.js and traditional server-side scripting environments (eg: PHP, Python, Ruby, etc).

Asynchronous Programming

Node.js uses a module architecture to simplify the creation of complex applications.

Chances are good that you are familiar with asynchronous programming; it is, after all, the “A” in Ajax. Every function in Node.js is asynchronous. Therefore, everything that would normally block the thread is instead executed in the background. This is the most important thing to remember about Node.js. For example, if you are reading a file on the file system, you have to specify a callback function that is executed when the read operation has completed.

You are Doing Everything!

Node.js is only an environment – meaning that you have to do everything yourself. There is not a default HTTP server, or any server for that matter. This can be overwhelming for new users, but the payoff is a high performing web app. One script handles all communication with the clients. This considerably reduces the number of resources used by the application. For example, here is the code for a simple Node.js application:

var i, a, b, c, max;

max = 1000000000;

var d = Date.now();

for (i = 0; i < max; i++) {
    a = 1234 + 5678 + i;
    b = 1234 * 5678 + i;
    c = 1234 / 2 + i;
}

console.log(Date.now() - d);

And here is the equivalent written in PHP:

$a = null;
$b = null;
$c = null;
$i = null;
$max = 1000000000;

$start = microtime(true);

for ($i = 0; $i < $max; $i++) {
    $a = 1234 + 5678 + $i;
    $b = 1234 * 5678 + $i;
    $c = 1234 / 2 + $i;
}

var_dump(microtime(true) - $start);

Now let’s look at the benchmark numbers. The following table lists the response times, in milliseconds, for these two simple applications:

Number of iterationsNode.jsPHP
1002.000.14
10’0003.0010.53
1’000’00015.001119.24
10’000’000143.0010621.46
1’000’000’00011118.001036272.19

I executed the two apps from the command line so that no server would delay the apps’ execution. I ran each test ten times and averaged the results. PHP is notably faster with a smaller amount of iterations, but that advantage quickly dissolves as the number of iterations increases. When all is said and done, PHP is 93% slower than Node.js!

Node.js is fast, but you will need to learn a few things in order to use it properly.


Modules

Node.js uses a module architecture to simplify the creation of complex applications. Modules are akin to libraries in C, or units in Pascal. Each module contains a set of functions related to the “subject” of the module. For example, the http module contains functions specific to HTTP. Node.js provides a few core modules out of the box to help you access files on the file system, create HTTP and TCP/UDP servers, and perform other useful functions.

Including a module is easy; simply call the require() function, like this:

var http = require('http');

Node.js is only an environment; you have to do everything yourself.

The require() function returns the reference to the specified module. In the case of this code, a reference to the http module is stored in the http variable.

In the above code, we passed the name of a module to the require() function. This causes Node to search for a node_modules folder in our application’s directory, and search for the http module in that folder. If Node does not find the node_modules folder (or the http module within it), it then looks through the global module cache. You can also specify an actual file by passing a relative or absolute path, like so:

var myModule = require('./myModule.js');

Modules are encapsulated pieces of code. The code within a module is mostly private – meaning that the functions and variables defined within them are only accessible from the inside of the module. You can, however, expose functions and/or variables to be used outside of the module. To do so, use the exports object and populate its properties and methods with the pieces of code that you want to expose. Consider the following module as an example:

var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

This code creates a PI variable that can only be accessed by code contained within the module; it is not accessible outside of the module. Next, two functions are created on the exports object. These functions are accessible outside of the module because they are defined on the exports object. As a result, PI is completely protected from outside interference. Therefore, you can rest assured that area() and circumference() will always behave as they should (as long as a value is supplied for the r parameter).


Global Scope

Node is a JavaScript environment running in Google’s V8 JavaScript engine. As such, we should follow the best practices that we use for client-side development. For example, we should avoid putting anything into the global scope. That, however, is not always possible. The global scope in Node is GLOBAL (as opposed to window in the browser), and you can easily create a global variable of function by omitting the var keyword, like this:

globalVariable = 1;
globalFunction = function () { ... };

Once again, globals should be avoided whenever possible. So be careful and remember to use var when declaring a variable.


Installation

Naturally, we need to install Node before we can write and execute an app. Installation is straight forward, if you use Windows or OS X; the nodejs.org website offers installers for those operating systems. For Linux, use any package manager. Open up your terminal and type:

sudo apt-get update
sudo apt-get install node

or:

sudo aptitude update
sudo aptitude install node

Node.js is in sid repositories; you may need to add them to your sources list:

sudo echo deb http://ftp.us.debian.org/debian/ sid main > /etc/apt/sources.list.d/sid.list

But be aware that installing sid packages on older systems may break your system. Be careful, and remove /etc/apt/sources.list.d/sid.list after you finish installing Node.


Installing New Modules

Node.js has a package manager, called Node Package Manager (NPM). It is automatically installed with Node.js, and you use NPM to install new modules. To install a module, open your terminal/command line, navigate to the desired folder, and execute the following command:

npm install module_name

It doesn’t matter what OS you have; the above command will install the module you specify in place of module_name.


The Hello World App

Naturally, our first Node.js script will print the text 'Hello World!' to the console. Create a file, called hello.js, and type the following code:

console.log('Hello World!');

Now let’s execute the script. Open the terminal/command line, navigate to the folder that contains hello.js, and execute the following command:

node hello.js

You should see 'Hello World!' displayed in the console.


HTTP Server

Let’s move on to a more advanced application; it’s not as complicated as you may think. Lets start with the following code. Read the comments and then the explanation below:

// Include http module.
var http = require("http");

// Create the server. Function passed as parameter is called on every request made.
// request variable holds all request parameters
// response variable allows you to do anything with response sent to the client.
http.createServer(function (request, response) {
	// Attach listener on end event.
	// This event is called when client sent all data and is waiting for response.
	request.on("end", function () {
		// Write headers to the response.
		// 200 is HTTP status code (this one means success)
		// Second parameter holds header fields in object
		// We are sending plain text, so Content-Type should be text/plain
		response.writeHead(200, {
			'Content-Type': 'text/plain'
		});
		// Send data and end response.
		response.end('Hello HTTP!');
	});
// Listen on the 8080 port.
}).listen(8080);

This code is very simple. You can send more data to the client by using the response.write() method, but you have to call it before calling response.end(). Save this code as http.js and type this into your console:

node http.js

Open up your browser and navigate to http://localhost:8080. You should see the text “Hello HTTP!” in the page.


Handling URL Parameters

As I mentioned earlier, we have to do everything ourselves in Node, including parsing request arguments. This is, however, fairly simple. Take a look at the following code:

// Include http module, 
var http = require("http"), 
// And url module, which is very helpful in parsing request parameters. 
	url = require("url"); 

// Create the server. 
http.createServer(function (request, response) { 
	// Attach listener on end event. 
	request.on('end', function () { 
		// Parse the request for arguments and store them in _get variable. 
		// This function parses the url from request and returns object representation. 
		var _get = url.parse(request.url, true).query; 
		// Write headers to the response. 
		response.writeHead(200, { 
			'Content-Type': 'text/plain' 
		}); 
		// Send data and end response. 
		response.end('Here is your data: ' + _get['data']); 
	}); 
// Listen on the 8080 port. 
}).listen(8080);

This code uses the parse() method of the url module, a core Node.js module, to convert the request’s URL to an object. The returned object has a query property, which retrieves the URL’s parameters. Save this file as get.js and execute it with the following command:

node get.js

Then, navigate to http://localhost:8080/?data=put_some_text_here in your browser. Naturally, changing the value of the data parameter will not break the script.


Reading and Writing Files

To manage files in Node, we use the fs module (a core module). We read and write files using the fs.readFile() and fs.writeFile() methods, respectively. I will explain the arguments after the following code:

// Include http module,
var http = require("http"),
// And mysql module you've just installed.
	fs = require("fs");

// Create the http server.
http.createServer(function (request, response) {
	// Attach listener on end event.
	request.on("end", function () {
		// Read the file.
		fs.readFile("test.txt", 'utf-8', function (error, data) {
			// Write headers.
			response.writeHead(200, {
				'Content-Type': 'text/plain'
			});
			// Increment the number obtained from file.
			data = parseInt(data) + 1;
			// Write incremented number to file.
			fs.writeFile('test.txt', data);
			// End response with some nice message.
			response.end('This page was refreshed ' + data + ' times!');
		});
	});
// Listen on the 8080 port.
}).listen(8080);

Node.js has a package manager, called Node Package Manager (NPM). It is automatically installed with Node.js

Save this as files.js. Before you run this script, create a file named test.txt in the same directory as files.js.

This code demonstrates the fs.readFile() and fs.writeFile() methods. Every time the server receives a request, the script reads a number from the file, increments the number, and writes the new number to the file. The fs.readFile() method accepts three arguments: the name of file to read, the expected encoding, and the callback function.

Writing to the file, at least in this case, is much more simple. We don’t need to wait for any results, although you would check for errors in a real application. The fs.writeFile() method accepts the file name and data as arguments. It also accepts third and fourth arguments (both are optional) to specify the encoding and callback function, respectively.

Now, let’s run this script with the following command:

node files.js

Open it in browser (http://localhost:8080) and refresh it a few times. Now, you may think that there is an error in the code because it seems to increment by two. This isn’t an error. Every time you request this URL, two requests are sent to the server. The first request is automatically made by the browser, which requests favicon.ico, and of course, the second request is for the URL (http://localhost:8080).

Even though this behavior is technically not an error, it is behavior that we do not want. We can fix this easily by checking the request URL. Here is the revised code:

// Include http module,
var http = require("http"),
// And mysql module you've just installed.
	fs = require("fs");

// Create the http server.
http.createServer(function (request, response) {
	// Attach listener on end event.
	request.on('end', function () {
		// Check if user requests /
		if (request.url == '/') {
			// Read the file.
			fs.readFile('test.txt', 'utf-8', function (error, data) {
				// Write headers.
				response.writeHead(200, {
					'Content-Type': 'text/plain'
				});
				// Increment the number obtained from file.
				data = parseInt(data) + 1;
				// Write incremented number to file.
				fs.writeFile('test.txt', data);
				// End response with some nice message.
				response.end('This page was refreshed ' + data + ' times!');
			});
		} else {
			// Indicate that requested file was not found.
			response.writeHead(404);
			// And end request without sending any data.
			response.end();
		}
	});
// Listen on the 8080 port.
}).listen(8080);

Test it now; it should work as expected.


Accessing MySQL Databases

Most traditional server-side technologies have a built-in means of connecting to and querying a database. With Node.js, you have to install a library. For this tutorial, I’ve picked the stable and easy to use node-mysql. The full name of this module is mysql@2.0.0-alpha2 (everything after the @ is the version number). Open your console, navigate to the directory where you’ve stored your scripts, and execute the following command:

npm install mysql@2.0.0-alpha2

This downloads and installs the module, and it also creates the node_modules folder in the current directory. Now let’s look at how we can use this in our code; see the following example:

// Include http module, 
var http = require('http'), 
// And mysql module you've just installed. 
	mysql = require("mysql"); 
	 
// Create the connection. 
// Data is default to new mysql installation and should be changed according to your configuration. 
var connection = mysql.createConnection({ 
	user: "root", 
	password: "", 
	database: "db_name"
}); 

// Create the http server. 
http.createServer(function (request, response) { 
	// Attach listener on end event. 
	request.on('end', function () { 
		// Query the database. 
		connection.query('SELECT * FROM your_table;', function (error, rows, fields) { 
			response.writeHead(200, { 
				'Content-Type': 'x-application/json' 
			}); 
			// Send data as JSON string. 
			// Rows variable holds the result of the query. 
			response.end(JSON.stringify(rows)); 
		}); 
	}); 
// Listen on the 8080 port. 
}).listen(8080);

Querying the database with this library is easy; simply enter the query string and callback function. In a real application, you should check if there were errors (the error parameter will not be undefined if errors occurred) and send response codes dependent upon the success or failure of the query. Also note that we have set the Content-Type to x-application/json, which is the valid MIME type for JSON. The rows parameter contains the result of the query, and we simply convert the data in rows to a JSON structure using the JSON.stringify() method.

Save this file as mysql.js, and execute it (if you have MySQL installed, that is):

node mysql.js

Navigate to http://localhost:8080 in your browser, and you should be prompted to download the JSON-formatted file.


Conclusion

Every function in Node.js is asynchronous.

Node.js requires extra work, but the payoff of a fast and robust application is worth it. If you don’t want to do everything on the lowest level, you can always pick some framework, such as >Express, to make it easier to develop applications.

Node.js is a promising technology and an excellent choice for a high load application. It has been proven by corporations, like Microsoft, eBay, and Yahoo. If you’re unsure about hosting your website/application, you can always use a cheap VPS solution or various cloud-based services, such as Microsoft Azure and Amazon EC2. Both of these services provide scalable environments at a reasonable price.

Don’t forget to comment if you have any questions!

Tags: node js
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • moncef

    Very very very good intorduction :), thanks a lot.

  • http://treinosmart.com Caio Ribeiro Pereira

    Nice post man!! I have a blog too, and I’m posting a mini-course about Node.js para leigos (Node.js for newbies), the only problem is that all posts are in portuguese.

    Take a look here: http://www.udgwebdev.com/nodejs-para-leigos/

    I hope everybody enjoy it!

    • https://twitter.com/jonocosa Jose Santos

      Fixe vou ler esse mini curso :)

  • http://numbus.co Alejandro Morales

    “Every function in Node.js is asynchronous.”?

    That’s not true.

    For example:

    fs -> All the methods have async and sync forms. (http://nodejs.org/api/all.html#all_file_system )

    So, you can define a sync function and it’ll be fine because it’s just javascript.

    • http://killahforge.com/ Maciej Sopyło
      Author

      Yes, I meant “Every function in Node.js base modules is asynchronous (with some of them having synchronous versions, but you shouldn’t use them).”. The point was to don’t encourage the reader to use synchronous ones, because it would block the thread.

    • http://jasdeep.ca Jasdeep Singh

      As per my understanding of Node from the original contributor Ryan Dahl – Everything in Node is non-blocking and Asynchronous.

      The fact that we have both Synchronous and Async forms of these functions in the concerned library is that the library is being explicit about it.

      fs.unlink()
      fs.unlinkSync()

      Above two functions are not the same and second one explicitly has a sync behaviour.

  • thecodingdude

    We were using nodejs for our project, but unfortunately, it doesn’t work well for MySQL in the sense that the code that is produced as a result is ugly and really difficult to follow.

    However, I am glad to see some tutorials for Nodejs as I feel it’s a language that is starting to gain popularity. Sadly, with the rate at which node is developing, I wouldn’t be surprised if this tutorial was outdated within a few months. :P

    • http://treinosmart.com Caio Ribeiro Pereira

      Did you try to use SequelizeJS for MySQL + Node.js?

      http://sequelizejs.com/

      But in my opinion the best DB for node.js is MongoDB or CouchDB.

      • george m

        Thanks for the heads-up on sequelizejs.com – a much needed ORM. I am hoping for a more generalized DAL (Data Application Layer) for both SQL and NoSQL someday. (Maybe one exists already?)

      • http://metacrash.com.au Marc Loney

        NoSQL databases integrate exceptionally well into the node.js projects considering most allow you to save direct representations of JSON objects.

        It is worth noting that most of these projects are still young so in most production situations I still tend to stick with a proven relational database such as PostreSQL.

      • http://treinosmart.com Caio Ribeiro Pereira

        I think there is no ORM for SQL and NoSQL.

        Both databases have different paradigms

  • https://timshomepage.net Timothy Warren

    Two minor issues:

    1. There are a set of synchronous functions in Node.js
    2. The content type for ajax is application/json.

  • AllDayHustle

    nodejitsu is also a great place to host your nodejs projects

  • king julien

    Thanks for the great post. More info about how to create and run a simple nodejs application on a live server would be great. For example create a simple chat application that would be accessible for everyone on the web.

  • http://www.crisialu.co.uk David Hughes

    Interesting article; especially the bit comparing the speed of PHP to node.js – although I can’t help but wonder how much use it is to the average developer. Most of the examples of users of node.js that they cite on their website are for sites that handle exceptionally high loads – the top 1% or so, I’d say. (Although I realise that there’s inevitably going to be a skew towards companies that you’ve actually heard of amongst such examples.)

    What I’m getting at, is, I rather suspect that the majority of developers are never going to face the problem of having to efficiently cope with the amount of traffic that, say, Ebay is subjected to, and so can probably afford to carry on using PHP. Even though we may loathe it.

    • george m

      Node.js was never positioned to be a replacement of PHP or any other server side technology. It is just a new technology targeted for apps needing heavy dose of real time asynchronous communication (high loads).

    • Mike McLin

      Performance from many visitors isn’t the only benefit. My main interest in node.js is the ability to use websockets. For example, a messaging system. Normally, you’d have to do something like keep hitting the server with AJAX requests to get refreshed data. With a websocket, you have an open connection (stateless) from the visitors browser to the server. I’ve just started exploring node and websockets, so my comments here might not be 100% accurate.

  • http://namangoel.com Naman Goel

    I just wanted to add that people just experimenting with node should look at something like Heroku which supports Node and has a free tier.
    It’s always great to get started with something for free. I agree that Heroku is probably not the cheapest solution once you need to scale. Amazon EC2 will probably be great for that. And search for it, there is specific tutorial on getting Node running EC2 somewhere on the interweb.

  • http://www.christher.se Christher

    Very nice introduction about node.js

    How can I call a node.js script from a website?

  • http://parkerituk.com Parker

    You also try https://openshift.redhat.com/app/ , that is one of my favourite.

    • http://treinosmart.com Caio Ribeiro Pereira

      Openshift and Heroku are the best clouds for Node.js

  • Chris

    Nice article ! The first one that was good to read an not totally nerdy. But the filewriter-example does not work on windows systems, i get “NaN” every time (but the file is written perfectly by js).

    • http://Bob.bob bob

      Ditto.. on a mac. It doesn’t seem to be a permissions thing..after all, it is updating the file “test.txt” but it is not incrementing an integer.

      Thanks for a GREAT beginner Tut. :-)

    • http://Bob.bob Bob

      AH! You need to put a 0 (zero) in the test.txt file…otherwise there is no integer data to add 1 to…

      -Bob

  • Chris

    Dude, seriously, you have a MASSIVE mistake in your little script. The line

    sudo apt-get install node

    does NOT install node.js ! It installs a totally unrelated piece of software. See the stackoverflow thread for that: http://stackoverflow.com/questions/2424346/getting-error-while-running-simple-javascript-using-node-framework.

    • http://metacrash.com.au Marc Loney

      The correct aptitude package is actually nodejs, not node but I’d highly recommend just going to http://nodejs.org/download/ and downloading the binaries or compiling from source.

  • http://hizup.com Kevin

    Thank you for this article, but I find PHP always better!
    JavaScript should not be used on the server side of a website.
    For the amount of code you should rather compare a Java Servlet and JavaScript code, the difference is much greater!

  • Ryan
    • Gregory

      The link at the bottom under “Read More” links back to this article. Which is why I find it interesting that “Written by Shadowtek Hosting and Design Solutions” appears at the top.

    • ya

      hmm, look very similiar

  • win

    thanks for your teaching

  • http://fabryz.com Fabryz

    http://nodejitsu.com/ is imho one of the best Node.js hosting environments, give it a try!

    • http://killahforge.com/ Maciej Sopyło
      Author

      Yes, but until they have paid options available (oh, I’m waiting for them since they were announced) it’s not suitable for enterprise-level applications (so you are free to experiment there, but don’t move your billion-visitors-per-month online shop there).

  • http://evanbyrne.com Evan

    Congratulations, that is quite possibly the most useless and poorly thought out benchmark I’ve ever seen.

    • J

      Maybe you should write a tutorial then!… Rather than just sitting in your pants at your computer trolling on the tutorials done by people who are trying to help others?

    • http://brianscaturro.com brian

      How about doing something useful and explaining why….

      • http://evanbyrne.com Evan

        Or how about you actually research the topic yourself, because you appear to be interested in it? I don’t give a rats ass which one operates faster, because I know they are both fast, and the database is going to be the bottleneck anyways.

      • http://www.facebook.com/PolygonRunner Juan Marco

        Quoting J Cole Morrison From the first comment on this page:
        “So I always appreciate it when another programmer demonstrates this
        empathy. It’s what keeps the programming field from looking like a
        landscape littered with insulting know-it-alls, but rather helpful
        gurus.”

    • http://www.cirkut.net/ Josh Allen

      It’s actually a great benchmark. When it comes down to it, yes, they’re both fast. However, as explained above, when it comes to larger scales, node.js will simply beat out the competition. Coming from Michigan myself, I can hardly believe someone from this great state would simply post a negative comment. How about something constructive?

      • Aristophrenia

        It looks to me like the time function for out putting the results is directly in the Var dump, this might slow down the result – maybe not, but maybe.

        We need to know if there is a delay in PHP outputting its var dump – so it would be better to calculate the time and then output it, rather than putting the calculation in the output.

        I know in many other languages the outputting of variables and trace statements can cause significant delays as some are more tightly knighted.

        Also why would you be integrating node.js as a websocket server when there are so many vastly superior web socket servers out there already such as WOWZER which offer incredible power ?

  • Horus

    nice post

  • teoman

    Can u please also add examples about Microsoft environment?

    We are using technologies such as IIS 7, Asp.Net, Sql Server 2008 on top of Windows 7?

    Thanks!

  • Alan

    Great article, thanks.

    Small point though, as Chris has said, running

    sudo apt-get install node

    on Ubuntu will install something that isn’t node.js.

    To install the proper node, with Ubuntu 12.04, this worked for me:

    sudo apt-get install nodejs

    A small but important distinction.

  • Peter

    i’d like to know how you did run the js vs. the php one,
    like did you loop within the code?
    did you execute the same script several times?

    can you please elborate on the examples?

  • Richard

    $a = null;
    $b = null;
    $c = null;
    $i = null;

    can be written as $a = $b = $c = $i = null;

    or leave them alone and they are null anyway.

  • Mihkel

    Well, nice to see some new content but this “node.js for beginners” has already been done several times in nettuts and all over the internet. I’d be glad if someone capable would start a session that goes beyond that basic “hello world server” stuff and covers things that developer needs to build apps in node.js. I have stopped trying to learn/use node.js because for me there is no such tutorial which would show me the best practices, development patterns, frameworks (express – yeah I know, but that’s it?). I enjoyed Jeffrey’s jQuery session … something like that for node.js would be awsome.

    • Marcin

      Mihkel is 100% right. I would like to see more advanced topics related to node.js, relational databases and how they work together.
      I agree that the node.js for beginners have been repeated too many times. We’d like to move past it and see some more advanced tutorials, either free or paid.

      • http://killahforge.com/ Maciej Sopyło
        Author

        As Node.js lover I will surely cover more advanced topics in the near future.

    • Lee

      I just started with node.js and there is TONS of info out there. You might expand your seraches to include Javascript.

  • http://www.scriptsnippets.com Sathesh Bm

    Nice post :) Have to learn and tut on Node.js

  • Qing Gao

    The “Reading and Writing Files” part of code behaviors differently on Chrome, Safari and Firefox. On Chrome, it always shows one number less than what is written into the file when clicking the fresh button.

  • sajay

    Great tutorial, Thank you very much. I tried few times getting started with node.js but I got stuck in between. This stuff is very well written for someone who is new with node.js.

  • J Cole Morrison

    Great tutorial!

    It may not be in-depth and advanced, but it does do something beautifully that most “node beginner” tutorials FAIL on – it explains Node’s concepts. The idea of “modules” and “async” programming aren’t really -hard- but they take a bit more digestion than most tutorials are willing to give. If you’ve been into code for a while, it’s easy to take the concepts of http, tcp, url parsing, databases, and what not for granted.

    So I always appreciate it when another programmer demonstrates this empathy. It’s what keeps the programming field from looking like a landscape littered with insulting know-it-alls, but rather helpful gurus.

  • http://www.genicode.com hamza khan

    Is there any tutorials of how to install nodejs.And where we need to store its files.
    its a basic question .

    thanks

    • anon101

      i’ve been searching for this too. too bad can’t find one

  • http://imstillreallybored.com joshbedo

    Awesome article only thing I didn’t like was the comparison of the PHP code you didn’t shorten the PHP as much as possibly. Ex the variables can be grouped the same as you did within JavaScript but you made JavaScript

  • http://allsnoringcures.com Sisir

    What are the use cases for node.js. I mean when do I use it rather than using normal jquery ajax?

    • http://killahforge.com/ Maciej Sopyło
      Author

      Uh, I don’t know where to start. You probably missed that Node.js is SERVER side code, and “normal jQuery ajax” is client side. Node.js is like Python, Ruby, PHP etc.

  • http://www.witnesstochange.co.uk Shaun

    General Question, what is the security like on NodeJS?

    I noticed that on the MySQL database example you included the information for the server in the JS file. If I looked at my requests would I see one for the NodeJS file and be able to download it and the information contained within in?

    • http://killahforge.com/ Maciej Sopyło
      Author

      Well, if you have nginx/apache webserver set up above Node and path to your script is accessible then anyone will be able to download it. Same situation if you have ftp server set up. Node itself is not allowing anyone to download anything, but it is also not preventing it. If you use any other server you have to make sure that your scripts are safe.

  • WIN

    hi,i like this tutorials very much.
    could i translate your (this)article into chineses?

  • sharad

    nice tutorial………….

  • http://twitter.com/thomasoriis Thomas Riis

    Nice tutorial. Really good way to explain the concepts. To make it better – you could mention that you press CTRL+C to restart the server in the terminal. It can really save a lot of typing. ParseInt wasn’t working I was getting NaN allover: Maybe this code can help others:

    http.data = http.data*1 === “NaN” ? 1 : http.data*1 + 1;

    Yes I am piggybacking the http reference ; ) Don’t like the idea of using variables without the use of var keyword.

    • hftty

      oio

      • luiop

        hjio

    • kishore

      parseInt will work if the file initially has 0 as its value

  • http://twitter.com/___imm_ David A. Viramontes

    Very nice introduction to node!
    Thanks!

  • Rajesh

    This us very useful guideline for beginners like me. In hope more information on server settings for node.js and other related stuffs.

  • Jason Young

    This appears in a couple code examples prior to including the fs module:

    // And mysql module you've just installed.

    Thanks for this tutorial!

  • Dread Head

    Great tutorial! It deconstructs the advantage of the event-driven model and asynchronous programming for the server side. Bravo

  • ashok

    Excellent start up for beginners !
    you’ve saved many hours of my time.
    Thanks for quick path to reach NODE.JS

  • Jackson

    Thanks for the awesome tutorial as always.

  • http://twitter.com/Mistcrafter Douglas Vaz

    Heroku provides a good hosting service for Node apps, including a very generous free plan

  • http://erasmusrios.webnode.com/ AaronRiggs

    Good one JavaScript should not be used on the server side of a website. For the amount of code you should rather compare a Java Servlet and JavaScript code, the difference is much greater.

    • Chris

      Yeah, and also compare the footprint (memory and CPU) of your JVM compared to running node.js. Totally justifies running javascript as opposed to a Java Servlet.

  • Test

    // Include http module,
    var http = require(‘http’),
    // And mysql module you’ve just installed.
    mysql = require(“mysql”);
    // Create the connection.
    // Data is default to new mysql installation and should be changed according to your configuration.
    var connection = mysql.createConnection({
    user: “root”,
    password: “”,
    database: “db_name”
    });
    // Create the http server.
    http.createServer(function (request, response) {
    // Attach listener on end event.
    request.on(‘end’, function () {
    // Query the database.
    connection.query(‘SELECT * FROM your_table;’, function (error, rows, fields) {
    response.writeHead(200, {
    ‘Content-Type’: ‘x-application/json’
    });
    // Send data as JSON string.
    // Rows variable holds the result of the query.
    response.end(JSON.stringify(rows));
    });
    });
    // Listen on the 8080 port.
    }).listen(8080);

  • samantha

    very easy and quick , loved your way!

  • mssb

    Very nice tutorial

  • kishore

    Good tutorial easy to understand awesome

  • Devang Gamit

    Great one………

  • BinaryPriest

    I can’t seem to get the example of querying the database to work.. here is the code I am using

    var http = require(‘http’);
    var mysql = require(‘mysql’);
    var con = mysql.createConnection({
    user: ‘XXXX’,
    passwrd: ‘XXXXXXXX’,
    database: ‘pathfinder’
    });

    http.createServer(function(req, res){
    req.on(‘end’, function(){
    con.query(‘SELECT race_id, race_name FROM race_main;’, function(err, rows, fields){
    res.writeHead(200, {‘Content-Type’ : ‘x-application/json’});
    });

    res.end(JSON.stringify(rows));
    });

    }).listen(1304);

    console.log(‘Data Server running on http://127.0.0.1:1304‘);

  • kunal

    Thanks dude such a awesome stuff here :)