22

From someone with few experience in JS, what do you recommend for learning Node.js?

I read a lot in the forum about event driven, non-blocking , async, callbacks, etc but I don't know what's that!

Where can I learn the basics in order to understand all that terms and in the future, node.js?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
donald
  • 23,587
  • 42
  • 142
  • 223
  • 4
    Start out with writing lots of javascript programs and caring about it doing well and proper. There's no point of even considering NodeJS if you do not understand javascript and corresponding techniques. I don't mean to be harsh, but thats what you need to learn; JavaScript and how it's used and used properly, those are the basics. Ergo, master javascript first ;) lots of awnsers on that on stackoverflow. – BGerrissen Sep 14 '10 at 10:17
  • Thank you for your comment. I find it hard to learn JS because I don't know what to do with that. If I want to learn Django,Rails, etc I know what to do, not JavaScript. Also, can you recommend a good book that can lay the basics for node.js knowledge as well? thank – donald Sep 14 '10 at 10:21
  • 1
    Just had a look at node.js. It is just usuing JS syntax like jQuery is. Do you feel a deep knowledge of JavaScript would be much more helpful when using node.js ? Anyway, the book to read is JavaScript: The definitive Guide – mplungjan Sep 14 '10 at 10:36
  • Not so much about the syntax itself but the internals. I need a good understanding of how it works. Maybe I can get that learning jQuery? – donald Sep 14 '10 at 10:42
  • Well the 'internals' are written in C++ and Ryan Dahl will keep it that way, but thats just the guts of the beast, stuff like server pugins and addons. Webapps put in NodeJS only run on JavaScript. – BGerrissen Sep 14 '10 at 11:14
  • As for 'mastering javascript' check this question: http://stackoverflow.com/questions/3696199/how-can-i-truly-master-javascript/3696765#3696765 – BGerrissen Sep 14 '10 at 11:16
  • @donald, jQuery is not a language, it's a toolkit and abstracts away from indepth javascript. So I'd say no, you won't learn a thing about JavaScript indepth by learning jQuery, but it's a starting point to jump to learning JavaScript however ;) – BGerrissen Sep 14 '10 at 11:18
  • Ok. Can you please create an answer in this post so I can make it the right answer for future reference? Thank you. – donald Sep 14 '10 at 11:23
  • If you want to learn JavaScript, then "JavaScript: Definitive Guide" is not a very good book as it's more as a manual, not a guide. You'd better start with something more tutorial-like ("PPK on JavaScript" for example) and keep the Definitive Guide handy as a reference to check some details of a specific function. – Andris Sep 14 '10 at 13:22
  • @donald: jquery is a wonderful thing, but it's possible to do a ton of stuff with jQuery even if you don't understand Javascript very well, or at all. jQuery is an awesome way to accomplish a lot of web front end things, but it's a really bad way to learn Javascript for purposes of doing node.js things on the server. – Unoti Sep 15 '10 at 04:02
  • possible duplicate of [How do I get started with Node.js](http://stackoverflow.com/questions/2353818/how-do-i-get-started-with-node-js) – Golo Roden Aug 14 '13 at 16:58

4 Answers4

53

The concepts you mention (event-driven, non-blocking, async, callbacks) aren't specific to JavaScript and understanding them in a more general context is valuable. They all revolve around gracefully handling resources over which we have no control.

Imagine waiting for data from a TCP connection, waiting for the OS to delete a file, or waiting for a user to click a button. If you programmed this in a step-by-step fashion (step-by-step is synchronous), you'd cruise along - "do step 1", "do step 2", "do step 3" - until you hit the step "wait for something to happen". At that point, your program would stop and refuse to budge until it received the data, received delete confirmation, or received the button click. In other words, the call blocks the program from proceeding. This is pretty inefficient considering there are likely other TCP connections, file operations, and UI actions that need our attention and don't depend on the item we're waiting for.

In many cases, it would be better to indicate we're interested in a resource and receive notifications outside of step-by-step instructions when the resource changes. From your list of concepts:

  • Events are changes in the resources we're interested in - our TCP connection received some data, the file delete is complete, or a user clicked a button.
  • Asynchronous calls tell the OS or runtime that we're interested in doing something with a resource. They are non-blocking - our program can work on something else while it waits for a change in the resource.
  • Callbacks are functions to be executed when the resource changes. An asynchronous resource call often accepts one or more references to callback functions (one for success, one for an error, etc...). When the resource changes, the runtime calls the appropriate callback.

We can see these concepts illustrated by renaming a file with node.js:

var fs = require('fs');

// args (current file name, new file name, callback function)
fs.rename('/tmp/hello', '/tmp/world', function (err) {
  // this occurs when the rename is complete
  if (err) throw err;
  console.log('rename complete');
});
console.log('step after rename');

The third argument may look strange. It's an unnamed (anonymous) function that will be called when the rename is complete.

Note that since fs.rename is asynchronous, it's impossible to tell if we'll see the 'rename complete' or 'step after rename' message first. That's the downside to event-driven/asynchronous programming - if we have a complex set of interdependent tasks, we need to be extremely careful to insure dependent tasks complete before the tasks that depend on them. The fact that the order of async call completion can change can lead to very subtle bugs.

See also:


Edit per donald's request:

The best way to understand node.js is to download, build, install, and use it. You'll need:

  • Mac OS or Linux. If your comfortable with Cygwin, that may also be an option but if you're running Windows I find it easier to run Linux in a virtual machine.
  • Git - not required but it makes fetching the code repository easy.
  • A way to debug your application. See this question. Initially, writing debug info to the console may work. Eventually, you'll want robust debugging.
  • An idea - what is it you want to do with node.js? If you're interested in an overview of its capabilities, browse its API.

Most tutorials focus on node.js's ability to quickly build an Http server:

Keep in mind that node.js fills a very particular niche - it's designed to build network programs. It may not be the right tool for other types of programs.

Community
  • 1
  • 1
Corbin March
  • 25,526
  • 6
  • 73
  • 100
  • 1
    Corbin, thank you for your explanation. Can you also add some other references that can help me towards the understanding of node.js? Something you believe is pertinent. Thanks – donald Sep 14 '10 at 20:53
  • +1. One minor note - "since fs.rename is asynchronous…" the "step after rename" log line will always execute first and appear first in the output as the execution context hasn't changed and console is synchronous in node v0.6+ – dc5 Aug 14 '13 at 16:07
  • How is it that this excellent explanatory answer has only 45 votes and the massive link dumps that are the top two answers on the "possible duplicate of ..." question have 3500 and 1400 votes each? – shoover Mar 21 '16 at 21:34
6

The basic concepts you need to understand to make progress with Node.js are the idea of events, event emitters, and event listeners.

In Node, most functions you can call are non-blocking. When you call fs.ReadStream(), for example, it returns a ReadableStream object. That object is an EventEmitter, so in order to do anything with the contents of the stream, you need to attach a listener to the object, which is a function that gets called when a particular event occurs.

So something like this works:

var fs=require('fs');
var stream = fs.createReadStream("/var/log/messages", { 'flags':'r' });
stream.addListener('data', function(someData) {
        console.log(someData);
});

This reads all of the text from the given file, and writes it to the console. When there is data to read from the stream, your function gets called, and is passed the data from the file.

Interestingly, once there is no more data to read from the file, the script exits. Node only stays running as long as there's a valid event listener attached to an emitter, or another asynchronous callback (like a timer) is active.

Mark Bessey
  • 19,598
  • 4
  • 47
  • 69
  • 1
    Thanks. What I don't understand from that example is where the function(someData) called and what is "someData". I don't see anything that passes information to the argument someData. thanks – donald Sep 14 '10 at 20:56
  • The stream object starts emitting those events, calling function(someData) behind the scenes. – Unoti Sep 15 '10 at 04:05
  • Right. Each event emitter has a list of event listeners for each event it can fire. When an event fires, each of the listeners are called. – Mark Bessey Sep 16 '10 at 21:04
4

«Javascript: The Good Parts» is one of the best books ever for learning the ins and outs of the language and not just DOM stuff.

Tyler Gillies
  • 1,857
  • 4
  • 22
  • 31
0

Well, this Stackoverflow question has a lot of awnsers in it that will teach you more about learning JS.

https://stackoverflow.com/questions/3696199/how-can-i-truly-master-javascript/3696765#3696765

JavaScript basics are actually the same basics as any other languages (hello world app, etc), the real difference lies in the 'advanced' areas of JavaScript.

Community
  • 1
  • 1
BGerrissen
  • 21,250
  • 3
  • 39
  • 40