B.2. Global objects

In Node.js, global objects are accessible throughout any application. You can use these objects at any point in a Node.js application. These objects can contain information about the application or filesystem. The following global objects are used most often in Node.js applications:

  • console prints to the console or standard output wherever your application is running.
  • __dirname returns the absolute path to the directory location on your machine, as follows:
    console.log(__dirname);
    >> /Users/Jon/Desktop
  • __filename provides the absolute path to the application directory on your machine, as follows:
    console.log(__filename);
    >> /Users/Jon/Desktop/filename_example.js
  • process references the process (thread) on which your application is running. This object is the main source of your application’s resources and connections to the filesystem.

Some objects appear to be similar to the Node.js global objects but come from other libraries required into your project. These objects are available in most Node.js applications. As you learn to work with the following objects, their use cases will make more sense:

  • module references the current module (JavaScript file) in which you’re working and allows you to access other variables within that file.
  • exports references a key/value pairing object to store a module’s functions or objects so they can be shared across other modules. Using this object is mostly the same as using module.exports. In the following example, accessibleFunction is exported for use in other modules:
    exports.accessibleFunction = () => {
      console.log("hello!");
    }
  • require allows you to import other modules’ code into a current module and gives you access to code written outside the current working file. The require keyword is used as follows:
    const http = require("http");
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset