Что такое module exports
Перейти к содержимому

Что такое module exports

  • автор:

#4 – Работа с модулями. Создание модуля

#4 – Работа с модулями. Создание модуля

Помимо сторонних модулей в Node JS есть еще встроенные модули. За урок мы научимся работать со встроенными модулями и дополнительно ознакомимся с построением своих собственных модулей.

Видеоурок

Если вы создаете большую программу на Node JS , то всегда необходимо разделять её на файлы. Каждый файл представляет из себя отдельный модуль, который наполнен различным функционалом. Вы можете подключать модули к другим файлам и использовать функции, прописанные в модулях.

Таким образом проект будет хорошо структурирован, а код будет более читабельным. Для создания модуля создайте новый файл, в котором пропишите именованные функции, переменные и другие конструкции.

const some = () =>

В примере выше создана именная функция. Для использования функции вне модуля её необходимо экспортировать.

Пример экспорта из модуля:

module.exports = some;

Для подключения модуля в других файлах необходимо использовать директиву require() и в ней прописать полный путь к файлу:

const some = require('./file'); // file - название подключаемого файла

Теперь вы можете использовать функцию some внутри файла с подключенным модулем.

Множественный экспорт

Совершенно неудобно создавать модуль для работы лишь с одним методом. Именно поэтому в Node JS существует множественный экспорт данных из модуля. Для реализации подобного существует 3 способа решения.

Во-первых, можно использовать конкретные свойства для вывода:

module.exports.add = add;

Здесь указывается имя свойства для экспорта, а также идет присваивание к нему значения. Значение может быть переменная или целая функция. Подобных свойств можно экспортировать бессчетное количество.

Во-вторых , можно экспортировать значения без создания переменных:

module.exports.some_value = "Экспорт сразу строки";

Точно также можно присваивать именованные функции для экспорта без создания переменных.

В-третьих , можно экспортировать сразу целый массив свойств и значений:

module.exports = < variable: 23.5, adding: adding >;

Таким образом мы экспортируем сразу множественное количество функций и переменных.

Чтобы воспользоваться экспортированными данными необходимо импортировать модуль в другой файл и создать переменную модуля. Далее вы можете через точку обращаться ко всем экспортированным данным:

const our_module = require('./src_file'); // Импорт модуля console.log(our_module.val); // Использование данных

Благодаря такой записи мы с легкостью можем прописывать в модуле все необходимые функции, после чего экспортировать их и вызывать в любых других файлах.

module.exports – How to Export in Node.js and JavaScript

Dillion Megida

Dillion Megida

module.exports – How to Export in Node.js and JavaScript

In programming, modules are components of a program with one or more functions or values.

These values can also be shared across the entire program and can be used in different ways.

In this article, I will show you how to share functions and values by exporting and importing modules in Node.js.

Why Export Modules?

You’ll want to export modules so that you can use them in other parts of your application.

Modules can serve different purposes. They can provide simple utilities to modify strings. They can provide methods for making API requests. Or they can even provide constants and primitive values.

When you export a module, you can import it into other parts of your applications and consume it.

For the rest of this article, we’ll focus on CommonJS Modules, the original approach to packaging modules in Node.js.

If you want to learn more about ES Modules (along with CommonJS modules), you can check out this in-depth guide.

How to Export Modules in Node

Node.js already exports in-built modules which include fs, path, and http to name a few. But you can create your own modules.

Node.js treats each file in a Node project as a module that can export values and functions from the file.

Say, for example, that you have a utility file utility.js with the following code:

// utility.js const replaceStr = (str, char, replacer) =>

utility.js is a module which other files can import things from. But utility.js currently does not export anything.

You can verify this by examining the global module object in each file. When you print the module global object in this utility file, you have:

console.log(module) // < // id: ".", // path: ". ", // exports: <>, // parent: null, // filename: ". ", // loaded: false, // children: [], // paths: [ // . // ], // > 

The module object has an exports property which, as you can see, is an empty object.

So any attempt to import anything from this file will throw an error.

The utility.js file has a replaceStr method which replaces characters in a string with some other characters. We can export this function from this module to be used by other files.

// utility.js const replaceStr = (str, char, replacer) => < const regex = new RegExp(char, "g") const replaced = str.replace(regex, replacer) return replaced >module.exports = < replaceStr >// or exports.replaceStr = replaceStr 

Now, replaceStr is available for use in other parts of the application. To use it, you import it like this:

const < replaceStr >= require('./utility.js') // then use the function anywhere 

module.exports vs exports in Node

You can export functions and values from a module by either using module.exports :

module.exports =

or by using exports :

exports.value1 = value1 exports.function1 = function1 

What’s the difference?

These methods are pretty identical. Basically, exports serves as a reference to module.exports . To understand this better, let’s populate the exports object by using the two ways of exporting values:

const value1 = 50 exports.value1 = value1 console.log(module) // < // id: ".", // path: ". ", // exports: < value1: 50 >, // parent: null, // filename: ". ", // loaded: false, // children: [], // paths: [ // . // ], // > const function1 = function() < console.log("I am a function") >module.exports = < function1, . module.exports >console.log(module) // < // id: ".", // path: ". ", // exports: < function1: [Function: function1] >, // parent: null, // filename: ". ", // loaded: false, // children: [], // paths: [ // . // ], // > 

There are two things to notice here:

  • The exports keyword is a reference to the exports object in the modules object. By doing exports.value1 = value1 , it added the value1 property to the module.exports object, as you can see in the first log.
  • The second log does not contain the value1 export anymore. It only has the function exported using module.exports . Why is this so?

module.exports = . is a way of reassigning a new object to the exports property. The new object only contains the function, so the value1 is no longer exported.

So what’s the difference?

Exporting values with just the exports keyword is a quick way to export values from a module. You can use this keyword at the top or bottom, and all it does is populate the module.exports object. But if you’re using exports in a file, stick to using it throughout that file.

Using module.exports is a way of explicitly specifying a module’s exports. And this should ideally only exist once in a file. If it exists twice, the second declaration reassigns the module.exports property, and the module only exports what the second declaration states.

So as a solution to the previous code, you either export like this:

// . exports.value1 = value1 // . exports.function1 = function1 
// . module.exports =

Wrap up

Each file in a Node.js project is treated as a module that can export values to be used by other modules.

module.exports is an object in a Node.js file that holds the exported values and functions from that module.

Declaring a module.exports object in a file specifies the values to be exported from that file. When exported, another module can import this values with the require global method.

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Dillion Megida

Dillion Megida

Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTISEMENT

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Node.js: В чём разница между exports и module.exports

В чем разница между exports и module.exports в Node.js

Для начала рассмотрим, что представляет собой объект модуля. Создадим файл run.js со следующим содержимым.

console.log(module);

Затем выполните файл с помощью node . Вы должны увидеть вывод, который выглядит примерно так:

$ node run.js 
Module
id: '.',
exports: >,
parent: null,
filename: '/Users/yaapa/projects/hacksparrow.com/run.js',
loaded: false,
children: [],
paths:
[ '/Users/yaapa/projects/hacksparrow.com/node_modules',
'/Users/yaapa/projects/node_modules',
'/Users/yaapa/node_modules',
'/Users/node_modules',
'/node_modules' ] >

Таким образом, похоже, что module — это контекстная ссылка на только что выполненный файл.

Вы заметили, что у него есть свойство exports ? Это пустой объект. Именно в нем вы определяете «импортируемые» объекты вашего модуля.

Теперь отредактируйте файл run.js и запустите его снова:

exports.a = 'A'; 
exports.b = 'B';
$ node run.js 
Module
id: '.',
exports: a: 'A', b: 'B' >,
...

Видно, что присвоение свойств объекту exports добавило эти свойства в modules.exports .

Это связано с тем, что exports — это ссылка на modules.exports .

exports.a = 'A'; 
console.log(exports === module.exports);
console.log(module.exports);
$ node run.js 
true
a: 'A' >

Таким образом, присвоение свойств объекту exports — это удобное сокращение, если вы хотите экспортировать объект из своего модуля:

module.exports =  
greet: function (name)
console.log(`Hi $name>!`);
>,

farewell: function()
console.log('Bye!');
>
>
exports.greet = function (name)  
console.log(`Hi $name>!`);
>

exports.farewell = function()
console.log('Bye!');
>

Определение свойств на exports , конечно, выглядит лучше, чем определение их на объекте, назначенном на module.exports .

Вам нравятся сюрпризы?

У вас нет выбора — exports не является ссылкой на modules.exports постоянно!

Если присвоить модулю module.exports что-либо, то exports перестанет быть ссылкой на него, и exports потеряет всю свою силу.

module.exports = a: 'A'>; 
exports.b = 'B';
console.log(exports === module.exports);
console.log(module)
$ node run.js 
false
Module
id: '.',
exports: a: 'A' >,
...

Итак, теперь вы знаете, что exports — это сокращение для ссылки на module.exports , если ваш модуль должен экспортировать объект. Это практически бесполезный объект, если ваш модуль экспортирует любой другой тип данных или вы присвоили модулю module.exports какое-либо значение.

  1. Node.js — объект module
  2. Node.js — module.exports

Что такое require и module.exports

Данная статья является прочтением и переосмыслением перевода Node.js, Require и Exports статьи-оригинала Node.js, Require and Exports.

Помимо этого, существует еще одна неплохая статья, посвященная данной тематике — Understanding module.exports and exports in Node.js.

require
module.exports

С помощью этих команд Node.js осуществляет взаимодействие своих модулей между друг другом.

require
module.exports

Ниже — краткое изложение статьи-оригинала …

В Node.js все штуки видны друг другу только в рамках одного и того же файла. Под штуками я подразумеваю переменные, функции, классы и их члены.

misc.js
const x = 5; let summ = function (value)  return value + x; >
summ

Дело в том, что Node.js состоит из блоков, называемых модулями; и каждый отдельный файл по своей сути — отдельный блок (модуль), чья область видимости изолирована от других таких же блоков (модулей).

Теперь перед тем как мы узнаем, как сделать эти штуки видимыми вне модуля, рассмотрим более подробно, как загружаются модули в Node.js.

require
require
let someModule = require('./some_module');
require
require
some_module
some_module
module.exports
const x = 5; let summ = function (value)  return value + x; >; module.exports.x = x; // сделали константу 5 доступной из других модулей module.exports.summ = summ; // сделали переменную summ доступной из других модулей
some_module
let someModule = require('./some_module');
someModule
x = 5
someModule.x
summ
someModule.summ

Есть ещё такой способ отдать штуки из нашего модуля:

let User = function (name, email)  this.name = name; this.email = email; >; module.exports = User;
User
User.name
User.email
module.exports
User

Разница между этими подходами не велика, но важна. Как видно, в данном случае мы экспортируем функцию напрямую:

module.exports.User = User; // vs module.exports = User;

Всё это к тому, что потом ее будет легче использовать:

var user = require('./user'); var u = new user.User(); // vs var u = new user();

Выгода от использования такого способа заключается в том, что в данном случае нам не важно, будет ли ваш модуль представлять контейнер c экспортируемыми значениями или нет.

Чтобы еще более красочно представить процесс взаимодействия модулей, давайте рассмотрим следующий пример:

let powerLevel = function (level)  return level > 9000 ? "it's over 9000" : level; >; module.exports = powerLevel;
require
let someModule = require('./powerlevel')(9000);

Что, по сути, является упрощенной записью следующего кода:

let someModule = require('./powerlevel'); someModule(9000);

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *