0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nodeでモジュールを読み込む、書き込む

0
Last updated at Posted at 2025-10-24

1. 外部パッケージ/組み込みモジュールを読み込む

node_modulesにあるパッケージ名またはNode.jsの組み込みモジュール名を使用します

JavaScript

 //'express'パッケージを読み込む例
const express = require("express"); 

 //組み込みの'fs' (ファイルシステム) モジュールを読み込む例
const fs = require("fs");

2. ローカルファイルを読み込む

自分で作成したファイル(モジュール)は、相対パスまたは絶対パスを指定します。



 同じディレクトリにある 'myUtils.js' を読み込む例
const utils = require("./myUtils"); 

 ひとつ上のディレクトリにある 'config/settings.js' を読み込む例
const settings = require("../config/settings");

モジュールのエクスポートと分割代入

複数の機能を持つモジュールを読み込む際、必要な機能だけを取り出す**分割代入(Destructuring Assignment)**が非常によく使われます。

export.js (モジュールを作成する側)
公開したい関数や変数をオブジェクトにまとめて、module.exportsに代入します。

 export.js

function sayHello() {
  console.log('hello from export.js');
}

function sayGoodbye() {
  console.log('goodbye from export.js');
}

// 複数の機能をオブジェクトとしてエクスポート
module.exports = {
    sayHello,   // キーと値が同じため {sayHello: sayHello} の短縮記法
    sayGoodbye
};

require.js (モジュールを読み込む側)

A. 通常の読み込み(分割代入なし)

エクスポートされたオブジェクト全体を受け取る

JavaScript
// require.js (通常)

const myModule = require('./export.js');
// myModule の中身は { sayHello: [Function], sayGoodbye: [Function] }

myModule.sayHello();   // 出力: hello from export.js
myModule.sayGoodbye(); // 出力: goodbye from export.js

分割代入による読み込み

// require.js (分割代入)

// エクスポートされたオブジェクトから 'sayHello' 関数だけを取り出す
const { sayHello } = require('./export.js');

sayHello(); // 出力: hello from export.js
// sayGoodbye(); // これはエラーになる (sayGoodbyeはインポートされていないため)

複数のプロパティを分割代入で読み込む

// require.js (複数の分割代入)

const { sayHello, sayGoodbye } = require('./export.js');

sayHello(); 
sayGoodbye();
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?