In Node.js, require()
and import
are two different ways of including external modules in your application.
require()
is a CommonJS module system function that is used to load and include external modules in a Node.js application. It is the most commonly used method of including modules in Node.js. require()
is a synchronous function that returns an object that contains the functionality provided by the module.
Here’s an example of using require()
to include the fs
(file system) module in a Node.js application:
const fs = require('fs');
import
is an ES6 (ECMAScript 2015) feature that is used to include external modules in a JavaScript application. import
is used in conjunction with the export
keyword, which is used to define the interface of the module that is being exported.
Here’s an example of using import
to include the fs
module in a Node.js application using an ES6 module:
import fs from 'fs';
Note that in order to use import
in a Node.js application, you need to use a transpiler like Babel to convert the ES6 code to CommonJS code that Node.js can understand.
The main differences between require()
and import
are:
require()
is a CommonJS feature, whileimport
is an ES6 feature.require()
is a synchronous function, whileimport
is an asynchronous function.require()
returns an object that contains the functionality provided by the module, whileimport
allows you to selectively import parts of the module using destructuring.