Chapter 2. Node programming fundamentals

 

This chapter covers

  • Organizing your code into modules
  • Handling one-off events with callbacks
  • Handling repeating events with event emitters
  • Implementing serial and parallel flow control
  • Using flow-control tools

Node, unlike many open source platforms, is easy to set up and doesn’t require much in terms of memory and disk space. No complex integrated development environments or build systems are required. Some fundamental knowledge will, however, help you a lot when starting out. In this chapter, we address two challenges that new Node developers face:

  • How to organize your code
  • How asynchronous programming works

In this chapter, you’ll learn important asynchronous programming techniques that will allow you to keep a tight rein on how your application executes. You’ll learn

  • How to respond to one-time events
  • How to handle repeating events
  • How to sequence asynchronous logic

We’ll start, however, with how you can tackle the problem of code organization through the use of modules, which are Node’s way of keeping code organized and packaged for easy reuse.

2.1. Organizing and reusing Node functionality

When creating an application, Node or otherwise, you often reach a point where putting all your code in a single file becomes unwieldy. When this happens, the conventional approach, as represented in figure 2.1, is to take a file containing a lot of code and try to organize it by grouping related logic and moving it into separate files.

2.2. Starting a new Node project

2.3. Fine-tuning module creation by using module.exports

2.4. Reusing modules by using the node_modules folder

2.5. Exploring caveats

2.6. Using asynchronous programming techniques

2.7. Handling one-off events with callbacks

2.8. Handling repeating events with event emitters

2.9. Challenges with asynchronous development

2.10. Sequencing asynchronous logic

2.11. When to use serial flow control

2.12. Implementing serial flow control

2.13. Implementing parallel flow control

2.14. Using community tools

2.15. Summary

sitemap