Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Understanding require() and modules

From: Node.js Essential Training

Video: Understanding require() and modules

When you're building a large application of any sort, you want to break it down into logical pieces. In this video, we'll take a look at how Node allows us to do this using modules. First, go to the Exercise files and go to Chapter 2, Video 2, then copy the Start folder to the Desktop. Once you have that folder there, open it up in a Text Editor, and then, also, go to the Command Line. I'm going to change directory to Desktop with a D, and then start. If I type in LS, it's showing all of the files and folders that are in that folder.

Understanding require() and modules

When you're building a large application of any sort, you want to break it down into logical pieces. In this video, we'll take a look at how Node allows us to do this using modules. First, go to the Exercise files and go to Chapter 2, Video 2, then copy the Start folder to the Desktop. Once you have that folder there, open it up in a Text Editor, and then, also, go to the Command Line. I'm going to change directory to Desktop with a D, and then start. If I type in LS, it's showing all of the files and folders that are in that folder.

So now we're ready to start exploring this code. Open up example1.js. At the top, on line 1, we're using that require function that we looked at in the previous video. This code is passing. /announce as the argument for require. What this is doing, is looking for a file called announce.js in our current directory. Since it's specified announce it's going to pull up announce.js here on the same level. So inside that file is all the code that's being exported when we call require.

So all of the code that's being set here in module.exports, is being set into this announce variable here on line 1 of example1.js. Let's take a closer look at announce.js. By setting module.exports here on line 1, we're telling Node that this is everything that we want to export from this file. Anything else that's in the file won't get exported. We're setting module.exports to be a function. We could return a function or an object, or any other variable that's valid JavaScript code.

This function takes one argument, and that argument is expected to be a string. And then finally, we're just calling console.log and then just adding the announcing string onto the beginning of the string that gets passed in. Now, let's go back to example1.js. Since we've exported a function, when we call require and set announce, announce gets set as a function. And then finally, on line 3, we can call announce, and pass in a string. Now, let's go to the Command Line and run this code. Type in node, space, example1.js.

So the output was announcing colon space and then string we passed in, Node essential training. Now let's take a look at a slightly different example. Open up example2.js. Just like in example1, we're calling require on the first line. This time we're passing in. /relay, and then we're setting the results to the relay variable. Let's go take a look at the code for relay. Now in this case there is not relay.js file, but there is a relay folder. So let's open that folder. Inside the relay folder is an index.js file.

Whenever you pass a path into require, it will look for either a. js variant of that name, or it will look for a folder that has an index.js file in it. So let's take a look at this index.js file now. On line 1, we're defining a variable called prefix. We are setting that prefix to the string relaying, colon and space. Now just like in announce.js, we're exporting a function, and this function takes a string. Then on line 4 working cat needing the prefix, the message. Now there's one problem with this code.

On line 1, we're just declaring prefix as a variable. Now just like in java script in a browser this is actually ending up as a global variable. The problem with a global variable, is that it can be overwritten anywhere in the code base. So back over here, we're actually overriding that prefix here on line 3. So instead of saying relaying as we have it defined in line 1 on index.js, it's going to say attention that's defined here on line 3. So now when relay gets called on line 5, it's going to say attention, ticket counter closes at 10 PM.

So let's run this code now. Type in node, space, example2.js, and now it's saying, attention, ticket counter closes at 10 PM. Let's fix this code now. Go back over to index.js, and instead of having it just be prefix, type in var space prefix. By typing in var, this is going to define prefix as a local variable. This way the prefix variable won't get clobbered by other variables named prefix elsewhere in our code base. Save the file, and let's go back to the Command Line.

I'm going to press the Up Arrow to bring up the last command. And now, I'm going to press Enter. Now, the output says, relaying. If we go back to example2, you'll notice that we're still setting the global prefix to say, attention. However, since we're now using a local variable here in the module, it doesn't matter. Now let's take a look at example3. Just like the other two examples, we're calling require and looking for a local module called proclaim. This is going to match up to proclaim.js. Back here in example3 however, you'll notice that we are calling it differently.

The say variable is being set to an object, and this object has two properties, softly and loudly. They're both functions. If we go back to proclaim.js, you'll notice that we're setting exports.softly and exports.loudly. We're not calling module exports because we want to set these individual properties that we're exporting. Another thing you'll notice, is that we're first declaring whisper as a function, and then we're setting softly to the value of whisper. When we go to use this module, the only thing that matters is what the name of the properties of exports are set to.

So now, let's go to the Command Line and run example3. Type in node, example3.js. Finally, let's have a look at example4. Like the other three examples, we're calling require. But this time, we're not specifying a dot and a slash. This is telling Node that we want to use a core module or we want to use a module that's been installed specifically for our project. In this case, the os module is a core module that ships with Node. We're setting the results to the variable os.

Then we're calling the type method of the os object. This is going to tell us what operating system the code is running on. So let's go to the Command Line and run this code now. Type in node example4.js. It's now saying that this code is running on Darwin, and Darwin is the operating system that Mac OS 10 is built on top of. Again, we're not using a dot and a slash to require the os module. Since it's a core module, we can call it from any file without worrying about the path. Modules form fundimental building blocks for programs running in Node.

The give you a way of arranging code into convenient, self contained objects. Coming up next we'll look at how the event loop keeps your Node programs running.

Show transcript

This video is part of

Image for Node.js Essential Training
Node.js Essential Training

52 video lessons · 13069 viewers

Joseph LeBlanc
Author

 
Expand all | Collapse all
  1. 3m 9s
    1. Welcome
      42s
    2. What you should know before watching this course
      57s
    3. Using the exercise files
      47s
    4. Using the challenges
      43s
  2. 18m 50s
    1. Why use Node.js?
      2m 1s
    2. Choosing a Node.js installation process
      4m 56s
    3. Installing Node.js on the Mac
      2m 5s
    4. Installing Node.js on Windows
      1m 43s
    5. Installing Node.js via Node Version Manager on Ubuntu Linux
      4m 45s
    6. Installing Node.js via Node Version Manager on a Mac
      3m 20s
  3. 13m 54s
    1. Exploring language additions to the V8 JavaScript engine
      3m 38s
    2. Understanding require() and modules
      6m 39s
    3. Understanding callback execution in the event loop
      3m 37s
  4. 12m 23s
    1. Initializing Node.js projects
      2m 37s
    2. Finding an NPM
      3m 30s
    3. Maintaining projects using the npm command
      6m 16s
  5. 21m 4s
    1. Creating modules with getters and setters
      6m 33s
    2. Understanding module caching and scopes
      6m 15s
    3. Implementing JavaScript creational patterns
      5m 8s
    4. Challenge: Leveraging module caching
      55s
    5. Solution: Leveraging module caching
      2m 13s
  6. 32m 27s
    1. Starting Express applications
      3m 42s
    2. Handling GET requests returning JSON
      3m 26s
    3. Navigating large datasets using request variables in routes
      5m 4s
    4. Modifying data through PUT requests
      4m 32s
    5. Supplying middleware to modify HTTP response headers
      4m 37s
    6. Generating HTML views in Jade
      8m 9s
    7. Challenge: List all records as JSON
      37s
    8. Solution: List all records as JSON
      2m 20s
  7. 25m 37s
    1. Evaluating unit testing methodologies
      3m 8s
    2. Isolating existing code for testing
      6m 47s
    3. Supplying helpers for test data
      2m 35s
    4. Writing unit tests with Mocha
      6m 5s
    5. Simulating HTTP requests with SuperTest
      7m 2s
  8. 28m 45s
    1. Connecting to MongoDB via Mongoose
      4m 16s
    2. Defining schemas for collections in Mongoose
      3m 47s
    3. Querying MongoDB collections
      5m 32s
    4. Persisting Express sessions through MongoDB and mongo-connect
      7m 6s
    5. Logging in to Express applications using Passport
      8m 4s
  9. 21m 47s
    1. Controlling the built-in REPL
      4m 18s
    2. Constructing a custom REPL
      5m 40s
    3. Receiving command-line arguments with Optimist
      6m 14s
    4. Building command-line tools
      3m 35s
    5. Challenge: Launch a custom REPL from a command
      41s
    6. Solution: Launch a custom REPL from a command
      1m 19s
  10. 15m 46s
    1. Emitting events and attaching listeners
      5m 32s
    2. Streaming chunked data through readable streams
      2m 33s
    3. Controlling readable streams
      1m 52s
    4. Piping readable data into writable streams
      2m 10s
    5. Handling duplex streams over TCP
      3m 39s
  11. 4m 6s
    1. Deploying projects to cloud hosting services
      2m 36s
    2. Finding Node.js resources
      1m 30s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Node.js Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.