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

Understanding module caching and scopes

From: Node.js Essential Training

Video: Understanding module caching and scopes

The first time node loads the module through require, it caches the result. This can be beneficial, but it can also create problems if you don't plan ahead. In this video we'll look at when caching is helpful, and when it's necessary to work around. So, first let's take a look at an example of when caching can get you into trouble. Let's go to exercise files, and in chapter 4 in video 2, there's a start folder, just copy the start folder to the desktop. And then open the start folder in your favorite text editor.

Understanding module caching and scopes

The first time node loads the module through require, it caches the result. This can be beneficial, but it can also create problems if you don't plan ahead. In this video we'll look at when caching is helpful, and when it's necessary to work around. So, first let's take a look at an example of when caching can get you into trouble. Let's go to exercise files, and in chapter 4 in video 2, there's a start folder, just copy the start folder to the desktop. And then open the start folder in your favorite text editor.

Take a look first at app.js. Now on line nine, I'm defining a variable called another flight. Another flight is being set to the value of what's returned by require flight. I'm using the exact same code that I'm using on line one, so you might expect that we would get a fresh copy of the module in another flight. And consequently, calling getInfo on anotherFlight on line 11 here, should give us a blank set of values. So let's go to the command line and run this code, and see what happens.

Go to terminal, and from here, type CD space. And, then I'm just going to drag the start folder in the terminal, which will give me the path to that folder. So, now I'm going to type node space app.js. Hm. You'll see the exact same data that's being set in the first flight, is also seen in another flight. Here's what's happening. In Index.js, the three variables are being set on line 1. No matter how many times you require this module, it's still going to refer to these three variables.

Now this is going to be a problem if you want to use this as a reusable module for several different flights. So let's take a look at some other code that we can use that will help us keep separate instances of flight information. Go back to the exercise files, and then in chapter four, video two there's a snippets folder. I'm going to replace the files in the start folder with the ones in snippets. So first I'm going to copy over app.js and replace it. I'm going to do the same for the flight folder.

I'm going to copy index.js from snippets on over to flight and replace that file. Now I'm going to go up a level and up another level. And now I'm going to open the Start folder in Sublime Text again. So now let's have a look at the new index.js. This time instead of exporting multiple functions, I'm exporting one function. And I'm using the module exports constant to do that. Notice that all of the code is contained within one function. This function takes one argument, called info.

On lines 3 through 11, I'm defining an object called values. This object has place holders for the number, the origin, the destination. The departure time and the arrival time, as well as the actual departure time and the actual arrival time. Then starting on line 13, I have a loop. See as this loop is a bit of a mess, we want to make sure that we only get valid, predetermined object properties To do this, we need to loop over each property and make sure we only get the ones we've defined.

So in this case, we only want the properties seen on lines four through ten. So, we're going to loop over each one of those properties and then find those properties in the info object that gets passed in on line one. So if that property is found, we then set values to that property. Lines 19 through 29 define three functions that we're going to use. Notice this time we don't have any setters. The setter is effectively defined here on lines 13 through 17.

On lines 20 through 25 we have two functions, one for triggering the departure time and one for triggering the arrival time. These are currently just set to the current time stamp. And then finally, on lines 26 through 28, we're returning the values that get set. One thing that's a little interesting to note here is on line 31 we're returning the functions. We're not returning any of the values that are defined here on lines 3 through 11. The only way we can get these values is by using the get information function that's defined on lines 26 through 28 and that's going to be available through the functions that we return from this module.

Now let's have a look at app.js. On line 1, we're requiring the flight module. Then on line 3 through 7, we're defining a flight. We're able to set each individual property without using a function. Next on line 9, were defining a new variable. We're using the flight function that's returned from the module And passing in the information we're defining on line 3. Then on line 11 we're calling the trigger depart method on that object. And then finally, on line 13, we're calling the get information method of that object, and then outputting the results to the console.

On lines 15 through 23 we're doing the same process again only for a different flight. On this flight, we're not calling the triggerDepart method. And then finally on line 25, we're calling the getInformation method of the first object so we can prove that these are separate flights. Let's go to the command line and run this code now. Type in node app.js and then, hit return. You'll notice that, on the first object, the actual depart property got set to the current time stamp.

The second object is completely separate. It has a different number, origin, and destination. And then, finally, the original object is exactly the same as it was before. We've now successfully created two different objects. This all works because we're using separate function scopes. Each time this function gets called a new function scope is created and that way the data from each flight is kept separate. While modules are cached whenever they're loaded for the first time it's possible to use a function to create a new variable scope.

In the next video, we'll look at an even more flexible way of creating multiple objects from the same module.

Show transcript

This video is part of

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

52 video lessons · 13248 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.