Home > Mobile >  Node js - Issue with my syntax in require(module) . When to use {} and when not to use {} in require
Node js - Issue with my syntax in require(module) . When to use {} and when not to use {} in require

Time:06-16

I have a query with the syntax in the require statement. Please refere the sample code below.

const nodemailer = require("nodemailer");
const {google} =require('googleapis');
const {OAuth2}=google.auth;

Some times , I see sample codes which use

const {<variable>} = require('moduleName')

Other times, I see like below

const <variable> = require('moduleName')

What is the difference between them? Thanks in Advance.

Grateful to the Developers Community.

CodePudding user response:

So, you use { } in this context when you want to do object destructuring to get a property from the exported object and create a module-level variable with that same name.

This:

const { google } = require('googleapis');

is a shortcut for this:

const __g = require('googleapis');
const google = __g.google;

So, within this context, you use the { google } only when you want the .google property from the imported module.

If you want the entire module handle such as this:

const nodemailer = require("nodemailer");

then, you don't use the { }. The only way to know which one you want for any given module is to consult the documentation for the module, the code for the module or examples of how to use the module. It depends entirely upon what the module exports and whether you want the top level export object or you want a property of that object.


It's important to realize that the { } used with require() is not special syntax associated with require(). This is normal object destructuring assignment, the same as if you did this:

// define some object
const x = { greeting: "hello" };    

// use object destructuring assignment to create a new variable
// that contains the property of an existing object
const { greeting } = x;

console.log(greeting);     // "hello

CodePudding user response:

When you import the function with {}, it means you just import one function that available in the package. Maybe you have've seen:

const {googleApi, googleAir, googleWater} = require("googleapis")

But, when you not using {}, it means you import the whole package, just write:

const google = require("googleapis")

So, let say when you need googleApi in your code. You can call it:

google.googleApi
  • Related