Different Ways to Import Files in a Node.js Project

Rmag Breaking News


In my last interview, the interviewer asked me about “Different Ways to Import Files in a Node.js Project”

There are many ways to import files, and I was familiar with all of them, but I could only recall three ways at that moment.

So, In this blog we’ll know some ways to import the files in a Node.js Project.

Using require()

This is the most common way to import files in Node.js.
We use require() followed by the path to the file we want to import.

const myModule = require(./myModule);

Using import (ES6)

With newer versions of Node.js and when using ECMAScript Modules (ESM), we can use the import keyword.

import myModule from ./myModule;

Using module.exports and require

When we want to export multiple things from a file in Node.js, we can use module.exports to export an object containing those things.
Then, we use require() to import that object and access its properties.

// In myModule.js
module.exports = {
myFunction: function() {
// Function code here
myVariable: Hello

// In another file
const myModule = require(./myModule);

Using export and import (ES6)

Similar to module.exports and require(), we can use export to export multiple things from a file and import to import them.

// In myModule.js
export const myFunction = function() {
// Function code here

export const myVariable = Hello;

// In another file
import { myFunction, myVariable } from ./myModule;

These are the main ways to import files in a Node.js project. Each method has its use cases, so it’s essential to understand them to choose the right one for your project.


If you liked this blog, please share it with others who might find it useful. You can also keep up with me for more stuff about JavaScript, React, Next.js, & Web Development.

You can find me on Twitter, LinkedIn, and GitHub.

Thanks for reading🌻

Leave a Reply

Your email address will not be published. Required fields are marked *