Thursday, August 31, 2017

Use of Export and Require


Export
  • The export statement is used when creating JavaScript modules to export functions, objects, or primitive values from the module so they can be used by other programs with the import statement
  • Along with export we also need require or import
Require

  •  Used to consume modules. It allows you to include modules into your programs. You can include built-in core Node.js modules, community-based modules (node_modules) and local modules

Example
In this file we have a function named as Authorize.
This function is exported using exports.auth
// Load client secrets from a local file.
var Authorize=function(){
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Gmail API.
authorize(JSON.parse(content), listLabels);
})

}
//Export the module
exports.auth=Authorize;

Wecan use it in another module as shown below
Use require to import
var user=require('./Authorize');

This is how we use the exported function
// Load client secrets from a local file.
var Authorize=function(){
    fs.readFile('client_secret.json', function processClientSecrets(err, content) {
      if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
      }
      // Authorize a client with the loaded credentials, then call the
      // Gmail API.
      authorize(JSON.parse(content), listLabels);
    })

}
//Export the module
exports.auth=Authorize;

No comments:

Post a Comment