Introducing module.exports | How to export in Node.js

Introducing module.exports | How to export in Node.js

Introduction

Using modules is an essential part of building complete applications and software systems using Node.js. In the absence of modules, your code would be fragmented and difficult to run, let alone maintain over time. But what is a module? And how exactly are you supposed to use module.exports to build your Node.js programs?

A module is a discrete program, contained in a single file in Node.js. Modules are therefore tied to files, with one module per file. Modules are available in other programming languages. Node.JS uses the CommonJS system of modules, but there are other module types used in the JavaScript ecosystem. The most prominent of these other module systems are the Asynchronous Module Definition (AMD) and the (ECMAScript 6) ES6 module systems.

As we will see, module.exports is an object that the current module returns when it is "required" in another program or module.

You can include functionality from other modules in any other module. To do so is referred to as "requiring" the module, which is simply calling for a certain special object representing the functionality of the module.

Requiring a Module

Node.js comes with a set of built-in modules that we can use in our code without having to install them. To do this, we need to require the module using the require keyword and assign the result to a variable. This can then be used to invoke any methods the module exposes.

For example, to list out the contents of a directory, you can use the file system module and its readdir method:

const fs = require('fs');
const folderPath = '/home/jim/Desktop/';

fs.readdir(folderPath, (err, files) => {
  files.forEach(file => {
    console.log(file);
  });
});

Note that in CommonJS, modules are loaded synchronously and processed in the order they occur.

How to creating and Exporting a Module

Now let’s look at how to create our own module and export it for use elsewhere in our program. Start off by creating a user.js file and adding the following:

const getName = () => {
  return 'Jim';
};

exports.getName = getName;

Now create an index.js file in the same folder and add this:

const user = require('./user');
console.log(`User: ${user.getName()}`);

Run the program using node index.js and you should see the following output to the terminal:

User: Jack


So what has gone on here? Well, if you look at the user.js file, you’ll notice that we’re defining a getName function, then using the exports keyword to make it available for import elsewhere. Then in the index.js file, we’re importing this function and executing it. Also notice that in the require statement, the module name is prefixed with ./, as it’s a local file. Also note that there’s no need to add the file extension.

Exporting Multiple Methods and Values

We can export multiple methods and values in the same way:


const getName = () => {
  return 'Jack';
};

const getLocation = () => {
  return 'Tokyo';
};

const dateOfBirth = '24.09.1984';

exports.getName = getName;
exports.getLocation = getLocation;
exports.dob = dateOfBirth;

And in index.js:

const user = require('./user');
console.log(
  `${user.getName()} lives in ${user.getLocation()} and was born on ${user.dob}.`
);

The code above produces this:

Jack lives in Tokyo and was born on 24.09.1984.


Notice how the name we give the exported dateOfBirth variable can be anything we fancy (dob in this case). It doesn’t have to be the same as the original variable name.

Variations in Syntax

I should also mention that it’s possible to export methods and values as you go, not just at the end of the file.

For example:


exports.getName = () => {
  return 'Jack';
};

exports.getLocation = () => {
  return 'Tokyo';
};

exports.dob = '24.09.1984';

And in index.js:

const { getName, dob } = require('./user');
console.log(
  `${getName()} was born on ${dob}.`
);

As you might expect, this logs:

Jack was born on 24.09.1984.
Exporting a Default Value

In the above example, we’re exporting functions and values individually. This is handy for helper functions that could be needed all over an app, but when you have a module that exports just the one thing, it’s more common to use module.exports:


class User {
  constructor(name, age, email) {
    this.name = name;
    this.age = age;
    this.email = email;
  }

  getUserStats() {
    return `
      Name: ${this.name}
      Age: ${this.age}
      Email: ${this.email}
    `;
  }
}

module.exports = User;

And in index.js:


const User = require('./user');
const jim = new User('Jim', 37, '[email protected]');

console.log(jim.getUserStats());

The code above logs this:

Name: Jack
Age: 35
Email: [email protected]

Differences Between module.exports and exports?

While working, you might come across the following syntax:


module.exports = {
  getName: () => {
    return 'Jack';
  },

  getLocation: () => {
    return 'Tokyo';
  },

  dob: '24.09.1984',
};

Here we’re assigning the functions and values we want to export to an exports property on module — and of course, this works just fine:

const { getName, dob } = require('./user');
console.log(
  `${getName()} was born on ${dob}.`
);

This logs the following:

Jack was born on24.09.1984.


So what is the difference between module.exports and exports? Is one just a handy alias for the other?

To better understand what I mean, let's change the code in index.js to record the value of the module:

console.log(module);


This produces:


Module {
  id: '.',
  exports: {},
  parent: null,
  filename: '/home/jack/Desktop/index.js',
  loaded: false,
  children: [],
  paths:
   [ '/home/jack/Desktop/node_modules',
     '/home/jack/node_modules',
     '/home/node_modules',
     '/node_modules' ] }

As you can see, module has an exports property. Let’s add something to it:

// index.js
exports.foo = 'foo';
console.log(module);

This outputs:

Module {
  id: '.',
  exports: { foo: 'foo' },
  ...


Assigning properties to exports also adds them to module.exports. This is because (initially, at least) exports is a reference to module.exports.

Conclusion

Today, modules have become an integral part of the JavaScript ecosystem . The use of module.exports allows us to export values, objects and styles from Node.js modules. Coupled with the use of require to import other modules, we have a complete ecosystem for composing large programs out of smaller parts. When we combine a number of modules that take care of unique parts of functionality, we can create larger, more useful, but easy to maintain applications and software systems.

Thanks for reading !

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Node.js for Beginners

Learn Node.js from Scratch (Step by Step)

Welcome to my course "Node.js for Beginners - Learn Node.js from Scratch". This course will guide you step by step so that you will learn basics and theory of every part. This course contain hands on example so that you can understand coding in Node.js better. If you have no previous knowledge or experience in Node.js, you will like that the course begins with Node.js basics. otherwise if you have few experience in programming in Node.js, this course can help you learn some new information . This course contain hands on practical examples without neglecting theory and basics. Learn to use Node.js like a professional. This comprehensive course will allow to work on the real world as an expert!
What you’ll learn:

  • Basic Of Node
  • Modules
  • NPM In Node
  • Event
  • Email
  • Uploading File
  • Advance Of Node

How to get started Internationalization in JavaScript with NodeJS

How to get started Internationalization in JavaScript with NodeJS

Tutorial showing how to use the Intl JS API in NodeJS (i18n). We'll install a module to unlock the Intl API languages for Node and test out RelativeTimeFormat to translate and localise relative times in JavaScript.

Tutorial showing how to use the Intl JS API in NodeJS (i18n). We'll install a module to unlock the Intl API languages for Node and test out RelativeTimeFormat to translate and localise relative times in JavaScript. I'll tell you how to get started with the built-in internationalization library in JS for Node 12 and higher. We'll change the locale to see how the translation works and test different BCP 47 language tags.

Internationalization is a difficult undertaking but using the Intl API is an easy way to get started, it's great to see this new API in the JS language and available for use. Soon, you'll be able to have confidence using it in the browser as modern browsers support the major Intl features. Have a look at the browser compatibility charts to see which browsers and versions of node are supported.

Use Intl.RelativeTimeFormat for language-sensitive relative time formatting.
#javascript #nodejs #webdevelopment

MDN Documentation:

https://developer.mozilla.org/en-US/d...

Full ICU NPM package:

https://www.npmjs.com/package/full-icu

What is WebAssembly? What does it mean for JavaScript and Node.JS?

What is WebAssembly? What does it mean for JavaScript and Node.JS?

What is WebAssembly? Is it going to replace JavaScript?! Signs say no, but it still has the potential to have a huge impact on JavaScript development in the browser and in Node.JS.

WebAssembly has been around for years but is only just starting to gain real traction in the developer space. What is WebAssembly? Is it going to replace JavaScript?! Signs say no, but it still has the potential to have a huge impact on JavaScript development in the browser and in Node.JS. Let’s walk through the how and why of this amazing new language feature through code and discussion.

Speaker: Mx Kassian Wren | DevRel, Cloudflare.

--

WebAssembly and the future of Web development

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.

WebAssembly gives developers a way to write optimized code routines, usually in C++. This is powerful ability, but it has a relatively narrow scope. It’s useful if you need to improve the performance of complex calculations. (For example, fastq.bio used WebAssembly to speed up their DNA sequencing calculations.) It’s also important if you’re porting high-performance games or writing an emulator that runs inside your browser. If this is all there were to WebAssembly, it wouldn’t be nearly as exciting — and it wouldn’t have any hope of displacing JavaScript. But WebAssembly also opens a narrow pathway for framework developers to squeeze their platforms into the JavaScript environment.

Here’s where things take an interesting turn. WebAssembly can’t sidestep JavaScript, because it’s locked into the JavaScript runtime environment. In fact, WebAssembly needs to run alongside at least some ordinary JavaScript code, because it doesn’t have direct access to the page. That means it can’t manipulate the DOM or receive events without going through a layer of JavaScript.

This sounds like a deal-breaking limitation. But clever developers have found ways to smuggle their runtimes in through WebAssembly. For example, Microsoft’s Blazor framework downloads a miniature .NET runtime as a compiled WASM file. This runtime deals with the JavaScript interop, and it provides basic services (like garbage collection) and higher-level features (layout, routing, and user interface widgets). In other words, Blazor uses a virtual machine that lives inside another virtual machine, which is either an Inception-level paradox or a clever way to create a non-JavaScript application framework that runs in the browser.

Blazor isn’t the only WebAssembly-powered experiment that’s out of the gate. Consider Pyodide, which aims to put Python in the browser, complete with an advanced math toolkit for data analysis.

This is the future. WebAssembly, which started out to satisfy C++, Rust, and not much more, is quickly being exploited to create more ambitious experiments. Soon it will allow non-JavaScript frameworks to compete with JavaScript-based standbys like Angular, React, and Vue.

And WebAssembly is still evolving rapidly. It’s current implementation is a minimum viable product — just enough to be useful in some important scenarios, but not an all-purpose approach to developing on the web. As WebAssembly is adopted, it will improve. For example, if platforms like Blazor catch on, WebAssembly is likely to add support for direct DOM access. Browser makers are already planning to add garbage collection and multithreading, so runtimes don’t need to implement these details themselves.

If this path of evolution seems long and doubtful, consider the lessons of JavaScript. First, we saw that if something is possible in JavaScript, it is done. Then, we learned that if something is done often enough, browsers make it work better. And so on. If WebAssembly is popular, it will feed into a virtuous cycle of enhancement that could easily overtake the native advantages of JavaScript.

It’s often said that WebAssembly was not built to replace JavaScript. But that’s true of every revolutionary platform. JavaScript was not designed to replace browser-embedded Java. Web applications were not designed to replace desktop applications.