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.Examples
Exporting a single function
File:
add.js
function add(a, b) {
return a + b;
}
module.exports = add;
File:
main.js
const add = require('./add.js');
console.log(add(1, 2)); // Output: 3
Exporting multiple functions
File:
math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add,
subtract
};
File:
main.js
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
const config = {
port: 3000,
apiUrl: 'https://api.example.com'
};
module.exports = config;
File:
main.js
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.
Examples
Example 1 - Exporting a single function
File:
add.js
export function add(a, b) {
return a + b;
}
File:
main.js
import { add } from './add.js';
console.log(add(1, 2)); // Output: 3
Example 2 - Exporting multiple functions
File:
math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
File:
main.js
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
export const config = {
port: 3000,
apiUrl: 'https://api.example.com'
};
File:
main.js
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:const fs = require('fs');
Reading files
Synchronous reading
To read a file synchronously, use the
fs.readFileSync()
method. This will block the execution of your program until the file is read.const data = fs.readFileSync('example.txt', 'utf-8');
console.log('File content:', data);
Asynchronous reading
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.fs.readFile('example.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log('File content:', data);
});
Reading with streams
Reading with streams can be useful for processing large files efficiently. To read a file using a stream, use the
fs.createReadStream()
method: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);
});
Writing files
Synchronous writing
To write to a file synchronously, use the
fs.writeFileSync()
method.const content = 'Hello, world!';
fs.writeFileSync('example.txt', content, 'utf-8');
console.log('File written successfully');
Asynchronous writing
To write to a file asynchronously, use the
fs.writeFile()
method.const content = 'Hello, world!';
fs.writeFile('example.txt', content, 'utf-8', (err) => {
if (err) throw err;
console.log('File written successfully');
});
Writing with streams
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: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);
});
Deleting files
To delete a file, use the
fs.unlink()
method.fs.unlink('example.txt', (err) => {
if (err) throw err;
console.log('File deleted successfully');
});
Node server MVC Basics
Express auth server structure
📗 Table of Contents
Importing Modules: CommonJS / ES ModulesCommonJS ImportsExporting a single functionExporting multiple functionsExporting an objectES Modules ImportsExample 1 - Exporting a single functionExample 2 - Exporting multiple functionsExample 3 - Exporting an objectFile ManipulationFS moduleReading filesSynchronous readingAsynchronous readingReading with streamsWriting filesSynchronous writingAsynchronous writingWriting with streamsDeleting filesNode server MVC BasicsExpress auth server structure