Require
The built-in require
function in Node facilitates the inclusion of modules from separate files, allowing the integration of core Node modules, community-based modules (node_modules), and local modules in a program. Primarily used for reading and executing JavaScript files, it returns the export object. Notable inbuilt modules include HTTP module, URL, query string, path, and others.
Syntax:
const express = require('express');
- To include the local module is as follows. For an instance, you require ‘abc’ module, without specifying a path.
require('abc');
Example: Node will look for abc.js in all the paths specified by module.paths in order.
require('abc');
Output:
- If node can’t find it:
Error: Cannot find module 'abc'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at repl:1:1
at ContextifyScript.Script.runInThisContext (vm.js:23:33)
at REPLServer.defaultEval (repl.js:336:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.onLine (repl.js:533:10)
- If node find it:
// It is the content of the file
w3wiki example for require
Difference between Node require and ES6 import and export
Node.js uses the CommonJS module system to organize code. This means when you want to use code from other files, you use methods like ‘require’. Additionally, Node.js also supports ‘ES6 import and export’ for this purpose. Let us understand in detail.
Table of Content
- Require:
- ES6 Import & Export
- Difference between node.js require and ES6 import and export: