Getting started with Node.jsnpmWeb Apps With ExpressFilesystem I/OExporting and Consuming ModulesExporting and Importing Module in node.jsInstalling Node.jsMySQL integrationReadlinepackage.jsonEvent EmittersAutoreload on changesEnvironmentCallback to PromiseExecuting files or commands with Child ProcessesCluster ModuleException handlingKeep a node application constantly runningUninstalling Node.jsnvm - Node Version ManagerhttpUsing StreamsDeploying Node.js applications in productionSecuring Node.js applicationsMongoose Libraryasync.jsFile uploadSocket.io communicationMongodb integrationHandling POST request in Node.jsSimple REST based CRUD APITemplate frameworksNode.js Architecture & Inner WorkingsDebugging Node.js applicationNode server without frameworkNode.JS with ES6Interacting with ConsoleCassandra IntegrationCreating API's with Node.jsGraceful ShutdownUsing IISNode to host Node.js Web Apps in IISCLINodeJS FrameworksgruntUsing WebSocket's with Node.JSmetalsmithParsing command line argumentsClient-server communicationNode.js Design FundamentalConnect to MongodbPerformance challengesSend Web NotificationRemote Debugging in Node.JSMysql Connection PoolDatabase (MongoDB with Mongoose)Good coding styleRestful API Design: Best PracticesDeliver HTML or any other sort of fileTCP SocketsHackBluebird PromisesAsync/AwaitKoa Framework v2Unit testing frameworksECMAScript 2015 (ES6) with Node.jsRouting ajax requests with Express.JSSending a file stream to clientNodeJS with RedisUsing Browserfiy to resolve 'required' error with browsersNode.JS and MongoDB.Passport integrationDependency InjectionNodeJS Beginner GuideUse Cases of Node.jsSequelize.jsPostgreSQL integrationHow modules are loadedNode.js with OracleSynchronous vs Asynchronous programming in nodejsNode.js Error ManagementNode.js v6 New Features and ImprovementEventloopNodejs Historypassport.jsAsynchronous programmingNode.js code for STDIN and STDOUT without using any libraryMongoDB Integration for Node.js/Express.jsLodashcsv parser in node jsLoopback - REST Based connectorRunning node.js as a serviceNode.js with CORSGetting started with Nodes profilingNode.js PerformanceYarn Package ManagerOAuth 2.0Node JS LocalizationDeploying Node.js application without downtime.Node.js (express.js) with angular.js Sample codeNodeJs RoutingCreating a Node.js Library that Supports Both Promises and Error-First CallbacksMSSQL IntergrationProject StructureAvoid callback hellArduino communication with nodeJsN-APIMultithreadingWindows authentication under node.jsRequire()Route-Controller-Service structure for ExpressJSPush notifications

Exporting and Importing Module in node.js

Other topics

Using a simple module in node.js

What is a node.js module (link to article):

A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file.

Now lets see an example. Imagine all files are in same directory:

File: printer.js

"use strict";

exports.printHelloWorld = function (){
    console.log("Hello World!!!");
}

Another way of using modules:

File animals.js

"use strict";

module.exports = {
    lion: function() {
        console.log("ROAARR!!!");
    }

};

File: app.js

Run this file by going to your directory and typing: node app.js

"use strict";

//require('./path/to/module.js') node which module to load
var printer = require('./printer');
var animals = require('./animals');

printer.printHelloWorld(); //prints "Hello World!!!"
animals.lion(); //prints "ROAARR!!!"

Using Imports In ES6

Node.js is built against modern versions of V8. By keeping up-to-date with the latest releases of this engine, we ensure new features from the JavaScript ECMA-262 specification are brought to Node.js developers in a timely manner, as well as continued performance and stability improvements.

All ECMAScript 2015 (ES6) features are split into three groups for shipping, staged, and in progress features:

All shipping features, which V8 considers stable, are turned on by default on Node.js and do NOT require any kind of runtime flag. Staged features, which are almost-completed features that are not considered stable by the V8 team, require a runtime flag: --harmony. In progress features can be activated individually by their respective harmony flag, although this is highly discouraged unless for testing purposes. Note: these flags are exposed by V8 and will potentially change without any deprecation notice.

Currently ES6 supports import statements natively Refer here

So if we have a file called fun.js

export default function say(what){
  console.log(what);
}

export function sayLoud(whoot) {
  say(whoot.toUpperCase());
}

…and if there was another file named app.js where we want to put our previously defined functions to use, there are three ways how to import them.

Import default

import say from './fun';
say('Hello Stack Overflow!!');  // Output: Hello Stack Overflow!!

Imports the say() function because it is marked as the default export in the source file (export default …)

Named imports

import { sayLoud } from './fun';
sayLoud('JS modules are awesome.'); // Output: JS MODULES ARE AWESOME.

Named imports allow us to import exactly the parts of a module we actually need. We do this by explicitly naming them. In our case by naming sayLoud in curly brackets within the import statement.

Bundled import

import * as i from './fun';
i.say('What?'); // Output: What?
i.sayLoud('Whoot!'); // Output: WHOOT!

If we want to have it all, this is the way to go. By using the syntax * as i we have the import statement provide us with an object i that holds all exports of our fun module as correspondingly named properties.

Paths

Keep in mind that you have to explicitly mark your import paths as relative paths even if the file to be imported resided in the same directory like the file you are importing into by using ./. Imports from unprefixed paths like

import express from 'express';

will be looked up in the local and global node_modules folders and will throw an error if no matching modules are found.

Exporting with ES6 syntax

This is the equivalent of the other example but using ES6 instead.

export function printHelloWorld() {
  console.log("Hello World!!!");
}

Contributors

Topic Id: 1173

Example Ids: 3787,7673,21944

This site is not affiliated with any of the contributors.