Node JS

Importing Modules: CommonJS / ES Modules

Compared to CommonJS, ES Modules allow you to import specific exports directly into your code, rather than importing the entire object and then accessing its properties.


CommonJS Imports

In CommonJS, the require() function is used to import a module. When you use require(), it returns the module.exports object from the imported module. This object contains all the exported values, functions, or objects that the module has provided.


Exporting a single function

File: add.js

jsx
function add(a, b) { return a + b; } module.exports = add;

File: main.js

jsx
const add = require('./add.js'); console.log(add(1, 2)); // Output: 3

Exporting multiple functions

File: math.js

jsx
function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } module.exports = { add, subtract };

File: main.js

jsx
const { add, subtract } = require('./math.js'); console.log(add(1, 2)); // Output: 3 console.log(subtract(1, 2)); // Output: -1

Exporting an object

File: config.js

jsx
const config = { port: 3000, apiUrl: 'https://api.example.com' }; module.exports = config;

File: main.js

jsx
const config = require('./config.js'); console.log(config.port); // Output: 3000


ES Modules Imports

In ES Modules, the import and from keywords work together to import specific exports from a module:


  • The import keyword is used to declare the named exports or the default export you want to import. You can import named exports by placing their names inside curly braces (). To import the default export, you simply write the desired variable name without the curly braces.
  • The from keyword is followed by a string that specifies the path to the module you're importing from.

Example 1 - Exporting a single function

File: add.js

jsx
export function add(a, b) { return a + b; }

File: main.js

jsx
import { add } from './add.js'; console.log(add(1, 2)); // Output: 3

Example 2 - Exporting multiple functions

File: math.js

jsx
export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b; }

File: main.js

jsx
import { add, subtract } from './math.js'; console.log(add(1, 2)); // Output: 3 console.log(subtract(1, 2)); // Output: -1

Example 3 - Exporting an object

File: config.js

jsx
export const config = { port: 3000, apiUrl: 'https://api.example.com' };

File: main.js

jsx
import { config } from './config.js'; console.log(config.port); // Output: 3000


File Manipulation

FS module

The fs module provides an API for working with the file system. To get started, you need to require the fs module:

jsx
const fs = require('fs');

To read a file synchronously, use the fs.readFileSync() method. This will block the execution of your program until the file is read.

jsx
const data = fs.readFileSync('example.txt', 'utf-8'); console.log('File content:', data);

To read a file asynchronously, use the fs.readFile() method. This will not block the execution of your program and will utilize a callback function.

jsx
fs.readFile('example.txt', 'utf-8', (err, data) => { if (err) throw err; console.log('File content:', data); });

Reading with streams can be useful for processing large files efficiently. To read a file using a stream, use the fs.createReadStream() method:

jsx
const readStream = fs.createReadStream('example.txt', 'utf-8'); readStream.on('data', (chunk) => { console.log('Read chunk:', chunk); }); readStream.on('end', () => { console.log('Finished reading the file'); }); readStream.on('error', (err) => { console.error('Error reading the file:', err); });


To write to a file synchronously, use the fs.writeFileSync() method.

jsx
const content = 'Hello, world!'; fs.writeFileSync('example.txt', content, 'utf-8'); console.log('File written successfully');

To write to a file asynchronously, use the fs.writeFile() method.

jsx
const content = 'Hello, world!'; fs.writeFile('example.txt', content, 'utf-8', (err) => { if (err) throw err; console.log('File written successfully'); });

Writing with streams is useful for processing large files or streaming data to a file. To write to a file using a stream, use the fs.createWriteStream() method:

jsx
const writeStream = fs.createWriteStream('example.txt', 'utf-8'); writeStream.write('Hello, world!'); writeStream.write('\nThis is another line.'); writeStream.end(() => { console.log('Finished writing the file'); }); writeStream.on('error', (err) => { console.error('Error writing the file:', err); });