DEV Community

Cover image for Different Ways to Import Files in a Node.js Project
Madhu Saini
Madhu Saini

Posted on

Different Ways to Import Files in a Node.js Project

Introduction

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.
  • Example:
const myModule = require('./myModule');
Enter fullscreen mode Exit fullscreen mode

Using import (ES6)

  • With newer versions of Node.js and when using ECMAScript Modules (ESM), we can use the import keyword.
  • Example:
import myModule from './myModule';
Enter fullscreen mode Exit fullscreen mode

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.
  • Example:
// In myModule.js
module.exports = {
  myFunction: function() {
    // Function code here
  },
  myVariable: 'Hello'
};

// In another file
const myModule = require('./myModule');
myModule.myFunction();
console.log(myModule.myVariable);
Enter fullscreen mode Exit fullscreen mode

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.
  • Example:
// In myModule.js
export const myFunction = function() {
  // Function code here
};

export const myVariable = 'Hello';

// In another file
import { myFunction, myVariable } from './myModule';
myFunction();
console.log(myVariable);
Enter fullscreen mode Exit fullscreen mode

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.

Conclusion

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šŸŒ»

Top comments (4)

Collapse
 
jangelodev profile image
JoĆ£o Angelo

Hi Madhu Saini,
Your tips are very useful
Thanks for sharing

Collapse
 
madhusaini22 profile image
Madhu Saini

Thank you so much <3

Collapse
 
grooms_nicholas profile image
Zack Grooms

Thanks for the useful tips, Madhu. I mostly use require, but I have used the others.

Collapse
 
madhusaini22 profile image
Madhu Saini

Glad you've learned something!