Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Node.js FAQ: Top Questions

6. What is the difference between require and import in Node.js?

require is used in CommonJS modules, while import is used in ES Modules, with differences in syntax, loading, and compatibility.

  • require (CommonJS):
    • Synchronous, dynamic loading.
    • Used in .js files by default.
    • Example: const fs = require("fs") .
  • import (ES Modules):
    • Asynchronous, static analysis.
    • Requires "type": "module" in package.json or .mjs files.
    • Example: import fs from "fs" .
  • Use Case: ES Modules for modern code, CommonJS for legacy.