dir.by  
Поиск >>

Компьютер, программы
→
Node.js (this is a web server that executes JS files)
 Пишем и подключаем наш модуль в Node.js 
посмотрели 13011 раз
обновлено: 21 April 2018
Шаг 1) Создадим свой модуль т.е. создадим новый файл myBook.js в текстовом редакторе
  JavaScript     Файл D:/NodeApp/myBook.js
// моя переменная
var bookName = 'Волшебник Земноморья';

// моя функция
function getBookInfo()
{
     return "Я читаю книгу " + bookName + " на 219 странице";
}

// экспортные переменные и функции
module.exports.name = bookName;
module.exports.info = getBookInfo;
Чтобы переменные и функции описанные в вашем модуле были доступны основной программе, мы их добавили в module.exports
Шаг 2) Создадим главный файл test.js в текстовом редакторе
  JavaScript     Файл D:/NodeApp/test.js
// подключаем свой модуль
var myBookModule = require('./myBook');

// подключаем встроенный модуль
var http = require('http');

// создаем web server
var server = http.createServer(function (request, response)
{
     response.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});

     // отображаем в браузер 'Волшебник Земноморья'
     response.write(myBookModule.name);

     // новая строка
     response.write('<BR>');

     // отображаем в браузер 'Я читаю книгу Волшебник Земноморья на 219 странице'
     response.write(myBookModule.info());

     // завершаем отображение в браузере
     response.end();
});

// прослушиваем web server
server.listen(3000);
Внимание!
Чтобы подключить наш модуль нужно писать путь ./
Это означает что мы подключаем свой модуль с текущей папки
var myBookModule = require('./myBook');

Встроенные модули подключаются просто по имени
var http = require('http');

Внимание!
Чтобы использовать переменные или функции вашего модуля нужно писать объект_модуля.экспротное_имя
Пример:
используем переменную
myBookModule.name

используем функцию
myBookModule.info()
Шаг 3) Запускаем Node.js сервер
Создадим новый файл run.bat в текстовом редакторе
  Файл D:/NodeApp/run.bat
node test.js
Шаг 4) Открываем браузер и вводим web адрес
Глобальные переменые в нашем модуле
Node.js предоставляет специальный объект global который виден для любого модуля.
  JavaScript     Наш модуль myBook.js
// мои переменные
var bookName = 'Волшебник Земноморья';
var bookPrice = '180';

// моя функция
function getBookInfo()
{
return "Я читаю книгу " + bookName + " на 219 странице";
}

// экспортные переменные и функции
module.exports.name = bookName;
module.exports.info = getBookInfo;

// глобальная переменная
global.price = bookPrice;
  JavaScript     Главный файл test.js
// подключаем свой модуль
var myBookModule = require('./myBook');

// подключаем встроенный модуль
var http = require('http');

// создаем web server
var server = http.createServer(function (request, response)
{
response.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});

// отображаем в браузер 'Волшебник Земноморья'
response.write(myBookModule.name);

// новая строка
response.write('<BR>');

// отображаем в браузер 'Я читаю книгу Волшебник Земноморья на 219 странице'
response.write(myBookModule.info());

// новая строка
response.write('<BR>');

// отображаем в браузер ГЛОБАЛЬНУЮ переменную '180'
response.write(price);

// завершаем отображение в браузере
response.end();
});

// прослушиваем web server
server.listen(3000);
К нашей глобальной переменной мы можем обращаться через global.price или просто price

По правилам хорошего написания программы не рекомендуется использование глобальных переменных, а лучше использовать экспортные переменные внутри модуля.
Наш модуль возвращающий только один объект
  JavaScript     Наш модуль myBook.js
// мой класс
function BookInfo()
{
     this.bookName = 'Волшебник Земноморья';
     this.bookPrice = '180';
    
     this.getBookInfo = function()
     {
return "Я читаю книгу " + this.bookName + " на 219 странице";
     }
}

// экспорт
module.exports = BookInfo;
  JavaScript     Главный файл test.js
// подключаем свой модуль
var myBookModule = require('./myBook');

// создаем объект
var book = new myBookModule();

// подключаем встроенный модуль
var http = require('http');

// создаем web server
var server = http.createServer(function (request, response)
{
response.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});

// отображаем в браузер 'Я читаю книгу Волшебник Земноморья на 219 странице'
response.end(book.getBookInfo());
});

// прослушиваем web server
server.listen(3000);
Вывод !!!
Вариант 1) Если в нашем новом модуле 'myBook.js' мы пишем
exports.экспортное_название1 = название_переменной1;
exports.экспортное_название2 = название_переменной2;
...
exports.экспортное_названиеA = название_функции1;
...
то в главном файле test.js мы используем экспортные_названия

Вариант 2) Если в нашем новом модуле 'myBook.js' мы пишем
exports = название_класса;
то в главном файле test.js мы НЕ используем экспортные_названия

Подробнее в примерах:
Наш новый модуль myBook.js
главный файл test.js
Вариант1
// мои переменные
var bookName = 'Волшебник моря';
var bookPrice = '180';

// моя функция
function getBookInfo()
{
    return "Я читаю книгу";
}

// экспортные переменные и функции
module.exports.name = bookName;
module.exports.price = bookPrice;
module.exports.info = getBookInfo;
// подключаем свой модуль myBook.js
var myBookModule = require('./myBook');

// используем свойства
myBookModule.name = "aaa";
myBookModule.price = "120";

// используем функциию
myBookModule.info();
Вариант2
// мой класс
function BookInfo()
{
    this.bookName = 'Волшебник моря';
    this.bookPrice = '180';

    this.getBookInfo = function()
    {
        return "Я читаю книгу"
    }
}

// экспорт
module.exports = BookInfo;
// подключаем свой модуль myBook.js
var myBookModule = require('./myBook');

// создаем объект класса
var book = new myBookModule();

// используем свойства
book.bookName;
book.bookPrice;

// используем функции
book.getBookInfo();
 
← Previous topic
How the require function works inside and what happens when we write require("ModuleName") in Node.js
 
Next topic →
"Express" module Node.js !!!!!!!!!!!!
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Новость "Черная пятница" Dreame в Беларуси – две недели скидок до 3400 рублей
 
• What is Node.js ?
• How do I find out the version of Node.js?
• Installing Node.js (download and install for Windows)
• How do I update my Node.js version (install the latest version)?
npm in Node.js
• What is npm in Node.js?
• How do I find the npm (Node.js) version?
• How do I update my npm version (install the latest version) ? | Node.js
• File package.json in Node.js
• Difference Between Tilde(~) and Lid(^) in package.json | Node.js
• File package-lock.json in Node.js
• "npm init" | Result: Creates an empty package.json file and populates that file with the default data | Node.js
• "npm install package_name" | Result: Installs JavaScript Library (Package) | For example, run "npm install jquery" | will add the jQuery library to the node_modules folder | Node.js
• "npm install" | Result: Installs the JavaScript libraries (packages) that are specified in the package.json | Node.js
• "npm list -g" (see a list of all installed global packages) | Node.js
• "npm install -g package_name" (global package install) | Node.js
• "npm uninstall -g package_name" (global package removal) | Node.js
• Run "npm run EvgenConvertCSS" | The package.json file like this: "scripts": {"EvgenConvertCSS": "node-sass --include-path scss 1.scss 1.css"} | Node.js
• Run "npm run EvgenMyCommand" | The file package.json like this: "scripts": {"EvgenMyCommand": "mkdir AAA"} | Node.js
• Run "npm run MyScript1" | The file package.json like this: "scripts": {"MyScript1": "npm run MyScript2"} | Node.js
• watch option in npm scripts (watch for changes in files)
Debugging NodeJS
• Debugging Node.js. Looking at variable values, function stack, breakpoints in Visual Studio Code
Writing Node.js application in a text editor (Notepad, Far)
• New Node.js app (create the app in a text editor, run in the console)
• Add the express package to the Node.js (in the Windows console)
• Uploading an html file and displaying it on the screen in Node.js (creating an application in a text editor, launching it in the console)
Using the socket.io module
• A simple application with socket.io in Node.js (creating an application in a text editor, running it in the console)
Writing Node.js project in Visual Studio Code
• New Node.js project (create the project in Visual Studio Code)
• Create a new Node.js project with websocket (create the project in Visual Studio Code) | client & server
Writing Node.js project in Visual Studio
• New Node.js project (create the project in Visual Studio)
• Add the express package to Node.js (in Visual Studio)
• Uploading an html file and displaying it on the screen in Node.js (project in Visual Studio)
• Chat (user writes a message and others get a message) using socket.io in Node.js (project in Visual Studio)
https localhost certificate
• Create https localhost certificate for nodejs
How modules are arranged in Node.js (require, exports)
• What are modules in Node.js ?
• How the require function works inside and what happens when we write require("ModuleName") in Node.js
Creating your own module in Node.js
• Writing and connecting your module to Node.js
Built-in Node.js modules
• "Express" module Node.js !!!!!!!!!!!!
Hosting Node.js on your website
• Hosting and installing Node.js on your website. Configuring Node.js in cPanel
• In Node.js I change the js file, and the old cached js file is displayed. Restart Node.js on your website in cPanel
• Add npm packages to the Node.js on your site (using cPanel)
• Error during WebSocket handshake... Hosting Node.js on your website
Heroku.com free service. Running your Node.js app on Heroku.com
• To use Heroku.com you need to install: Git, Node.js
• Registration on the Heroku.com website
• Installing the command line "Heroku CLI"
• "Heroku CLI" is very slow for Windows
• Running your Node.js app on Heroku.com
WWW sites for learning Node.js
• Sites to learn Node.js

  Ваши вопросы присылайте по почте: info@dir.by