Code Monkey home page Code Monkey logo

nodejs-require-caching's Introduction

Node.js - caching data in required files or modules

Quick example to demonstrate that a file required into different files in a Node.js application is in fact the same closure.

In reality this means that if anything is stored or cached in the the required file, any file that requires it can access the cached info.

This is very useful when building applications, but can take you by surprise if you're not aware that this is how it works!

Running

Simply run node app.js in the comman line.

Note: Use Node.js v 6+ to avoid ES6 warnings

What's happening

app.js requires a files called util.js.

util.js has a local variable myData initialised to null. It exposes two functions:

  1. set - takes a single parameter and assigns the value to the myData variable.
  2. get - returns the myData variable

app.js calls the set method of util sending it a string value.

app.js calls the get method of util and outputs it as a console log.

app.js requires another file file2.js.

file2.js requires in the util.js file.

file2.js calls the get method of util and outputs it as a console log.

Both console.log statements have the same value, as the data is cached inside the util.js file.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.