avatarHussain Arif

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3582

Abstract

eadable to humans.</p><p id="fd1e"><b>Third parameter </b>is the callback function. What are callback functions? Learn about them <a href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">here</a> . First we check whether there are errors(maybe error in reading file or etc.) and then print them out if they are present, otherwise the contents of the file are printed out if everything’s okay.</p><p id="81f8"><a href="https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback">fs documentation</a></p><h1 id="3276">Using Third Party Modules</h1><p id="560c">First install a module through npm</p><p id="ef96">Lets install <i>express </i>as an example</p><div id="49be"><pre><span class="hljs-built_in">npm</span> i express</pre></div><p id="c733">Then <i>require() </i>like so:</p><div id="aa05"><pre><span class="hljs-variable">const</span> <span class="hljs-variable">express</span> = <span class="hljs-function"><span class="hljs-title">require</span>(<span class="hljs-string">'express'</span>)</span></pre></div><p id="8d1c">Note: I’ve written a basic guide for NPM, see <a href="https://readmedium.com/the-basics-of-npm-a32ee1d79901?sk=5aebd80f871bdc4ca990565e9730dc58">here</a></p><h1 id="4ba3">Using local modules</h1><p id="7c8a">To use your own modules(<b>local modules</b>) , you have to ‘<i>export</i>’ it first. You can export <b>strings, functions , variables</b> etc.</p><p id="9538">Syntax is as follows:</p><div id="597c"><pre>module.<span class="hljs-keyword">exports</span> = <<span class="hljs-keyword">Object</span> <span class="hljs-keyword">to</span> be exported> </pre></div><p id="3640">The most simple example</p><p id="fa98">Create a module called ‘<i>message.js’ </i>and another called ‘<i>app.js’</i> .</p><p id="60af"><i>message.js</i></p><div id="e877"><pre><span class="hljs-attr">module.exports</span> = <span class="hljs-string">"Hello World"</span> </pre></div><p id="2f35"><i>app.js</i></p><div id="ccf1"><pre><span class="hljs-keyword">const</span> <span class="hljs-keyword">message</span> = require(<span class="hljs-string">'./message.js'</span>) console.log(<span class="hljs-keyword">message</span>)</pre></div><p id="469c">Run the code <i>app.js </i>on the command line. As a result, “Hello World” will be printed out.</p><p id="45a1">To export a<b> function</b>, the code is similar:</p><p id="fbfc"><i>message.js</i></p><div id="75d9"><pre>module.exports = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">"Hello World"</span>) }</pre></div><p id="16c9"><i>app.js</i></p><div id="e082"><pre><span class="hljs-variable">const</span> <span class="hljs-variable">message</span> = <span class="hljs-function"><span class="hljs-title">require</span>(<span class="hljs-string">"./message.js"</span>)</span> <span class="hljs-function"><span class="hljs-title">message</span>();</span></pre></div><h1 id="a7de">Exports object</h1><p id="c93a"><b><i>exports </i></b>is an <b><i>object. </i></b>Thus , you can add properties to it.<i> module.exports</i></p><p id="e8bb"><i>message.js</i></p><div id="ccc0"><pre>module.exports.sayHello = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'Hello'</span>) }</pre></div><div id="5b53"><pre>module<span class="hljs-selector-class">.exports</span><span class="hljs-selector-class">.sayCu

Options

stomMessage</span> = <span class="hljs-built_in">function</span>(message) { console<span class="hljs-selector-class">.log</span>(message) } module<span class="hljs-selector-class">.exports</span><span class="hljs-selector-class">.myVariable</span> = <span class="hljs-number">4</span> module<span class="hljs-selector-class">.exports</span> = { firstName: <span class="hljs-string">'Hussain'</span> lastName: <span class="hljs-string">'Arif'</span> }</pre></div><p id="1089"><i>app.js</i></p><div id="39d1"><pre>const <span class="hljs-keyword">message</span> = require(<span class="hljs-string">'./message.js'</span>) <span class="hljs-keyword">message</span>.sayHello() <span class="hljs-keyword">message</span>.sayCustomMessage(<span class="hljs-string">'Goodbye!'</span>); console.<span class="hljs-meta">log</span>(<span class="hljs-keyword">message</span>.myVariable) console.<span class="hljs-meta">log</span>(<span class="hljs-keyword">message</span>.firstName + <span class="hljs-string">' '</span> + <span class="hljs-keyword">message</span>.lastName)</pre></div><p id="ee3a">In summary, to use local modules:

  1. use <b>module.exports </b>to export it
  2. use <b>require() </b>to use its functionality.</p><h2 id="68ea">The require method can be used to import:</h2><div id="cc15"><pre><span class="hljs-keyword">const</span> filesystem = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>) <span class="hljs-comment">// core module</span></pre></div><div id="c4dd"><pre><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>) <span class="hljs-comment">// npm module</span></pre></div><div id="e4bf"><pre><span class="hljs-keyword">const</span> <span class="hljs-keyword">server</span> = require(<span class="hljs-string">'./boot/server.js'</span>) <span class="hljs-comment">// server.js file with a relative path down the tree</span></pre></div><div id="a706"><pre><span class="hljs-keyword">const</span> <span class="hljs-keyword">server</span> = require(<span class="hljs-string">'../boot/server.js'</span>) <span class="hljs-comment">// server.js file with a relative path up the tree</span></pre></div><div id="87c0"><pre>const <span class="hljs-keyword">server</span> = require(<span class="hljs-string">'/var/www/app/boot/server.js'</span>) // <span class="hljs-keyword">server</span>.js file <span class="hljs-keyword">with</span> an absolute <span class="hljs-type">path</span></pre></div><div id="fb23"><pre><span class="hljs-keyword">const</span> <span class="hljs-keyword">server</span> = require(<span class="hljs-string">'./boot/server'</span>) <span class="hljs-comment">// file if there's the server.js file</span></pre></div><div id="98a3"><pre><span class="hljs-keyword">const</span> routes = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../routes'</span>) <span class="hljs-comment">// index.js inside routes folder if there's no routes.js file</span></pre></div><div id="f74b"><pre><span class="hljs-keyword">const</span> databaseConfigs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./configs/database.json'</span>) <span class="hljs-comment">// JSON file</span></pre></div><p id="423b"><b>Note: To require a third party/NPM module do not include “.” or “..” in your parameters.The modules will already be present in the “node_modules” directory located in your project</b></p><p id="a6f8">That’s all for today. See you later!</p><p id="2dd8">Stay home, save lives.</p></article></body>
Source

Node.JS Modules & Exports

What are modules?

A module in NodeJS is a simple or complex JavaScript file which can be used throughout your web app. In short, each module is just a file with JavaScript code in it.

There are three types of modules:

Core Modules:

These type of modules include bare minimum functionalities in Node.JS. Common examples can be:

http : to build a simple HTTP server paths : to deal with file paths fs : work with simple file input/output operations

Local Modules

These are the modules built by you: the programmer.

It’s good practice to write modules as it promotes cleanliness of your code and make your code modular(you can reuse your module in other projects without a lot of additional effort)

Third Party Modules

These types of modules are built by the programming community. They mostly include complex code so that the programmer can add functionality to his app without writing it himself. This way, he saves time as well.

How can I use these modules?

When using modules, you simply use the function require()

const myModule = require("moduleName")

Example:

Lets use fs (file system module) to read a simple text file as an example:

Open notepad, write any piece of text on it and then save it anywhere. Let’s name it “demofile.txt”. Open your code editor and write this piece of code and save it as the same directory as your .txt file:

const fs = require("fs")
fs.readFile("demofile.txt" , {encoding : 'utf-8'} , function(err,data) {
if(err) console.log(err)
console.log(data)
})

now save it as “fsExample.js” and run it on your command line

node fsExample

(For more details on running your code through your command line, I’ve written a guide)

As a result, you’ll see the contents of your text file printed out

Details of the readFile method:

The first parameter is the name of the text file you wish to read

Second parameter is your options : here, encoding method is ‘utf-8’ so that text can be printed out. If you don’t specify the options, it will print out buffer values, which are unreadable to humans.

Third parameter is the callback function. What are callback functions? Learn about them here . First we check whether there are errors(maybe error in reading file or etc.) and then print them out if they are present, otherwise the contents of the file are printed out if everything’s okay.

fs documentation

Using Third Party Modules

First install a module through npm

Lets install express as an example

npm i express

Then require() like so:

const express = require('express')

Note: I’ve written a basic guide for NPM, see here

Using local modules

To use your own modules(local modules) , you have to ‘export’ it first. You can export strings, functions , variables etc.

Syntax is as follows:

module.exports = <Object to be exported> 

The most simple example

Create a module called ‘message.js’ and another called ‘app.js’ .

message.js

module.exports = "Hello World" 

app.js

const message = require('./message.js')
console.log(message)

Run the code app.js on the command line. As a result, “Hello World” will be printed out.

To export a function, the code is similar:

message.js

module.exports = function() {
console.log("Hello World")
}

app.js

const message = require("./message.js")
message();

Exports object

exports is an object. Thus , you can add properties to it. module.exports

message.js

module.exports.sayHello = function() {
console.log('Hello')
}
module.exports.sayCustomMessage = function(message) {
console.log(message)
}
module.exports.myVariable = 4
module.exports = {
firstName: 'Hussain' 
lastName: 'Arif'
}

app.js

const message = require('./message.js')
message.sayHello()
message.sayCustomMessage('Goodbye!');
console.log(message.myVariable)
console.log(message.firstName + ' ' + message.lastName)

In summary, to use local modules: 1) use module.exports to export it 2) use require() to use its functionality.

The require method can be used to import:

const filesystem = require('fs') // core module
const express = require('express') // npm module
const server = require('./boot/server.js') // server.js file with a relative path down the tree
const server = require('../boot/server.js') // server.js file with a relative path up the tree
const server = require('/var/www/app/boot/server.js') // server.js file with an absolute path
const server = require('./boot/server') // file if there's the server.js file
const routes = require('../routes') // index.js inside routes folder if there's no routes.js file
const databaseConfigs = require('./configs/database.json') // JSON file

Note: To require a third party/NPM module do not include “.” or “..” in your parameters.The modules will already be present in the “node_modules” directory located in your project

That’s all for today. See you later!

Stay home, save lives.

Node
Nodejs
Programming
Coding
JavaScript
Recommended from ReadMedium