Join Joseph LeBlanc for an in-depth discussion in this video Understanding modules, part of Node.js First Look.
- View Offline
Let's go to the command-line and run it. Change directory into desktop and run the script. Do node and then script.js. So again, it's showing the text This script is running on Node.js version 0.8.1 on a Darwin-based operating system, and it's getting Darwin from that OS module. However, you're not limited to the modules that ship with Node.js. There are other modules that you can install as a part of your project.
Here, we have a project that's written in Node.js. There is another script file, and it's requiring node-markdown, and then it's assigning it to the parser object. Then finally, we're calling parser. markdown to change this markdown code into HTML, and then when we have the HTML, we're spitting it out on the console. To run the script, do node project/script.js. So you'll notice it transformed all of this markdown into HTML.
Another thing you'll notice is the package.json file. This file tells us about our program and also allows us to define the dependencies that our program needs. The NPM command can use this file to automatically find all the Node modules that you want to use, and install them. It installs them in the node_modules folder within your project. So you'll notice, we specified node- markdown as the dependency, and then NPM created the node-markdown folder.
NPM put all of the code for node-markdown in this folder. Finally, in addition to core modules and modules available through NPM, you can define local modules. This is useful for when you want to separate your data from your code. This is an example of a local module that we've written. We're using the exports global provided by Node and then assigning properties to that global. These properties will be available as properties of our module.
So in fibonacci.js, we have the first few numbers of the Fibonacci sequence. In script.js, we're requiring the Fibonacci module. Notice, we have a dot and a forward slash before Fibonacci. That tells Node to load a local module rather than looking in Node modules or in the core module collection. We're then requiring that Fibonacci file, and assigning it to the sequence object. Finally, we're accessing that data property from sequence, and spitting it out to the console.
- Using the Socket.IO Node package to achieve "live" effects like Facebook notifications
- Scraping web sites using jQuery without a browser