Database Reference
In-Depth Information
Working with Node
Despite being JavaScript, programmers coming from the browser side of
webapplicationdevelopmentareoftenstymiedbyNode'sprocessingmodel.
The same is true of engineers coming from other web application
frameworks, such as Ruby on Rails. The reason for the difficulty is Node's
event-driven callback style. This style of programming is very different than
what most programmers are used to, so it helps to begin with an overview of
the style to understand how Node works.
NOTE
Node is a rapidly evolving project with regular releases. Some of these
releases introduce or remove functionality, which makes compatibility
between releases difficult. This topic assumes a version of Node similar
to the 0.10 application programming interfaces (APIs).
Callback-Driven Programming
In most languages, such as Java or Python, operations are assumed to be
blocking. So, when code asks for a line from a file, it sits and waits until that
line is completely available and then returns the line to the program. For
instance, the following code for reading a file from an InputStream named
stream in Java might look like this:
InputStreamReader reader = new
InputStreamReader(stream);
BufferedReader lines = new BufferedReader(reader);
while(lines.ready()) {
var line = lines.readLine();
//Do something with the line here
}
In Node, this style of programming is generally unavailable because I/O
is assumed to be non-blocking. (There are exceptions, but they are rare.)
Instead, Node interfaces either take an object or respond to events. For
example, in the following code a file is opened, but there is no function
to read the next line as there would be in, say, a Java program. Instead,
Search WWH ::




Custom Search