Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Get Certified Upgrade Teachers Spaces
   ❮     
     ❯   

Node.js Tutorial

Node HOMENode IntroNode Get StartedNode JS RequirementsNode.js vs BrowserNode Cmd LineNode V8 EngineNode ArchitectureNode Event Loop

Asynchronous

Node AsyncNode PromisesNode Async/AwaitNode Errors Handling

Module Basics

Node ModulesNode ES ModulesNode NPMNode package.jsonNode NPM ScriptsNode Manage DepNode Publish Packages

Core Modules

HTTP ModuleHTTPS ModuleFile System (fs)Path ModuleOS ModuleURL ModuleEvents ModuleStream ModuleBuffer ModuleCrypto ModuleTimers ModuleDNS ModuleAssert ModuleUtil ModuleReadline Module

JS & TS Features

Node ES6+Node ProcessNode TypeScriptNode Adv. TypeScriptNode Lint & Formatting

Building Applications

Node FrameworksExpress.jsMiddleware ConceptREST API DesignAPI AuthenticationNode.js with Frontend

Database Integration

MySQL Get StartedMySQL Create DatabaseMySQL Create TableMySQL Insert IntoMySQL Select FromMySQL WhereMySQL Order ByMySQL DeleteMySQL Drop TableMySQL UpdateMySQL LimitMySQL Join
MongoDB Get StartedMongoDB Create DBMongoDB CollectionMongoDB InsertMongoDB FindMongoDB QueryMongoDB SortMongoDB DeleteMongoDB Drop CollectionMongoDB UpdateMongoDB LimitMongoDB Join

Advanced Communication

GraphQLSocket.IOWebSockets

Testing & Debugging

Node Adv. DebuggingNode Testing AppsNode Test FrameworksNode Test Runner

Node.js Deployment

Node Env VariablesNode Dev vs ProdNode CI/CDNode SecurityNode Deployment

Perfomance & Scaling

Node LoggingNode MonitoringNode PerformanceChild Process ModuleCluster ModuleWorker Threads

Node.js Advanced

MicroservicesNode WebAssemblyHTTP2 ModulePerf_hooks ModuleVM ModuleTLS/SSL ModuleNet ModuleZlib ModuleReal-World Examples

Hardware & IoT

RasPi Get StartedRasPi GPIO IntroductionRasPi Blinking LEDRasPi LED & PushbuttonRasPi Flowing LEDsRasPi WebSocketRasPi RGB LED WebSocketRasPi Components

Node.js Reference

Built-in ModulesEventEmitter (events)Worker (cluster)Cipher (crypto)Decipher (crypto)DiffieHellman (crypto)ECDH (crypto)Hash (crypto)Hmac (crypto)Sign (crypto)Verify (crypto)Socket (dgram, net, tls)ReadStream (fs, stream)WriteStream (fs, stream)Server (http, https, net, tls)Agent (http, https)Request (http)Response (http)Message (http)Interface (readline)

Resources & Tools

Node.js CompilerNode.js ServerNode.js QuizNode.js ExercisesNode.js SyllabusNode.js Study PlanNode.js Certificate

Node.jsModules


What is a Module in Node.js?

Modules are the building blocks of Node.js applications, allowing you to organize code into logical, reusable components. They help in:

  • Organizing code into manageable files
  • Encapsulating functionality
  • Preventing global namespace pollution
  • Improving code maintainability and reusability

Node.js supports two module systems: CommonJS (traditional) and ES Modules (ECMAScript modules).

This page covers CommonJS, whileES Modules are covered separately.


Core Built-in Modules

Node.js provides several built-in modules that are compiled into the binary.

Here are some of the most commonly used ones:

  • fs - File system operations
  • http - HTTP server and client
  • path - File path utilities
  • os - Operating system utilities
  • events - Event handling
  • util - Utility functions
  • stream - Stream handling
  • crypto - Cryptographic functions
  • url - URL parsing
  • querystring - URL query string handling

To use any built-in module, use therequire() function:

Example: Using Multiple Built-in Modules

const http = require('http');

Now you can use the module's features, like creating a server:

Example: Simple HTTP Server

http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Hello World!');
}).listen(8080);
Run Example »

Creating and Exporting Modules

In Node.js, any file with a.js extension is a module. You can export functionality from a module in several ways:

1. Exporting Multiple Items

Add properties to theexports object for multiple exports:

Example: utils.js

// Exporting multiple functions
const getCurrentDate = () => new Date().toISOString();

const formatCurrency = (amount, currency = 'USD') => {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: currency
  }).format(amount);
};

// Method 1: Exporting multiple items
exports.getCurrentDate = getCurrentDate;
exports.formatCurrency = formatCurrency;

// Method 2: Exporting an object with multiple properties
// module.exports = { getCurrentDate, formatCurrency };

2. Exporting a Single Item

To export a single item (function, object, etc.), assign it tomodule.exports:

Example: logger.js

class Logger {
  constructor(name) {
    this.name = name;
  }

  log(message) {
    console.log(`[${this.name}] ${message}`);
  }

  error(error) {
    console.error(`[${this.name}] ERROR:`, error.message);
  }
}

// Exporting a single class
module.exports = Logger;

3. Using Your Modules

Import and use your custom modules usingrequire() with a relative or absolute path:

Example: app.js

const http = require('http');
const path = require('path');

// Importing custom modules
const { getCurrentDate, formatCurrency } = require('./utils');
const Logger = require('./logger');

// Create a logger instance
const logger = new Logger('App');

// Create server
const server = http.createServer((req, res) => {
  try {
    logger.log(`Request received for ${req.url}`);

    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write(`<h1>Welcome to our app!</h1>`);
    res.write(`<p>Current date: ${getCurrentDate()}</p>`);
    res.write(`<p>Formatted amount: ${formatCurrency(99.99)}</p>`);
    res.end();
  } catch (error) {
    logger.error(error);
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Internal Server Error');
  }
});

// Start server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  logger.log(`Server running at http://localhost:${PORT}`);
});

Module Loading and Caching

Node.js caches modules after the first time they are loaded. This means that subsequentrequire() calls return the cached version.

Module Resolution

When you require a module, Node.js looks for it in this order:

  1. Core Node.js modules (likefs,http)
  2. Node modules innode_modules folders
  3. Local files (using./ or../ prefix)

Run the example in your terminal:

C:\Users\<Your Name>> node demo_module.js

Visithttp://localhost:8080 to see the result in your browser.


Best Practices

Module Organization

  • Keep modules focused on a single responsibility
  • Use meaningful file and directory names
  • Group related functionality together
  • Useindex.js for module entry points

Export Patterns

  • Prefer named exports for utilities
  • Use default exports for single-class modules
  • Document your module's API
  • Handle module initialization if needed

Summary

Modules are a key concept in Node.js. They enable you to organize code into reusable, maintainable units.

By understanding how to create, export, and use modules effectively, you can build scalable and well-structured applications.

Key takeaways:

  • Node.js uses CommonJS modules by default
  • Userequire() to import andmodule.exports to export
  • Modules are cached after first load
  • Follow best practices for module organization and structure




×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp