Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Exporting with module.exports | Section
Node.js Fundamentals

bookExporting with module.exports

メニューを表示するにはスワイプしてください

When you want to share functions, objects, or values from one file so that another file can use them, you use module.exports in Node.js. This is the foundation of how modules communicate. You define your functions or objects in one file, then assign them to module.exports. Any file that uses require to load this module will receive whatever you assigned to module.exports.

mathUtils.js

mathUtils.js

copy

Start by creating a function or object you want to export. In the example above, the add function and the calculator object are defined in mathUtils.js. By assigning an object containing both add and calculator to module.exports, you make both available to other files.

When another file, such as app.js, uses require('./mathUtils'), Node.js loads the module and returns the value of module.exports. This means mathUtils in app.js is the object you exported, so you can call mathUtils.add(5, 3) or mathUtils.calculator.subtract(10, 4).

You can export a single value, like a function, or an object containing multiple values. If you assign a new value to module.exports, that is what will be returned by require. Always remember: only what you attach to module.exports will be accessible outside the module.

Note
Note

In Node.js, exports is just a shortcut reference to module.exports. You can use exports.greet = ... to add properties, but if you reassign module.exports directly, the shortcut no longer applies.

// Valid: adding a property
exports.greet = () => "Hello!";

// Invalid: reassigning exports breaks the link
exports = () => "Hello!"; // Won't work
question mark

How do you export a function or object from a Node.js module so it can be used in another file?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  12

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  12
some-alt