
Mastering the foundation of express
# What is node js?
Node.js is a single-threaded, open-source, cross-platform runtime environment. It runs on the V8 JavaScript runtime engine.
# Why node.js is popular?
- We can use JavaScript on the server side.
- Build highly scalable-backed applications.
- It is single-threaded, event-driven, and works non-blocking I/O
- Perfect building data-intensive, streaming application.
# node.js modules
- operating system Module (os)
- File system module (fs)
- Path Module (path)
- HTTP Module (http)
- URL Module (url)
- Utilities Module (util)
# What is a module?
A module is an isolated and reusable block of code that has its own scope.
- Local Modules (We create)
- Built-in modules (come with node js)
- Third-party modules(created by others)
How to import export in node js :
// file name - local-1
const add1 = (num1, num2) => {
return num1 + num2
}
const minus = (num1, num2) => {
return num1 - num2
}
module.exports = {
minus, add1
};
const {add1, minus} = require("./local-1");
const result = add1(5,6)
const result2 = minus(5,6)
console.log(result);
console.log(result2);
Path Module :
By the path module, we can easily access the path of the file.
const path = require('path')
console.log(path)
<ref *1> {
resolve: [Function: resolve],
normalize: [Function: normalize],
isAbsolute: [Function: isAbsolute],
join: [Function: join],
relative: [Function: relative],
toNamespacedPath: [Function: toNamespacedPath],
dirname: [Function: dirname],
basename: [Function: basename],
extname: [Function: extname],
format: [Function: bound _format],
parse: [Function: parse],
sep: '\\',
delimiter: ';',
win32: [Circular *1],
posix: <ref *2> {
resolve: [Function: resolve],
normalize: [Function: normalize],
isAbsolute: [Function: isAbsolute],
join: [Function: join],
relative: [Function: relative],
toNamespacedPath: [Function: toNamespacedPath],
dirname: [Function: dirname],
basename: [Function: basename],
extname: [Function: extname],
format: [Function: bound _format],
parse: [Function: parse],
sep: '/',
delimiter: ':',
win32: [Circular *1],
posix: [Circular *2],
_makeLong: [Function: toNamespacedPath]
},
_makeLong: [Function: toNamespacedPath]
}
Path module has many methods. We just talking about some important Path module methods.
var path = require('path');
var moduleName= path.basename('file_path');
console.log(moduleName);
path.basename method returns the path extension.
path.dirname(path)
This method returns the directory name of the path. For example:
const result = path.dirname('file_path');
console.log(result);
# File system module, synchronous vs asynchronous
Reading file text(Synchronous way)
const fs = require('fs');
const readText = fs.readFileSync('./read.txt', 'utf-8')
console.log(readText);
Written file text(Synchronous way)
// Writting a text
const writeText = fs.writeFileSync('./write.txt', readText + 'Write this is')
console.log(writeText);
Reading file text(Asynchronous way)
fs.readFile('./read.txt', 'utf-8', (err, data) => {
if (err) {
throw Error('error reading')
}
console.log(data);
})
Written file text(Asynchronous way)
// write file asynchronouos way
const text = 'Tested text';
fs.writeFile('./test.txt', text, err => {
if (err) {
console.error(err);
}
});
Event-Driven Architecture
Node.js is an event-driven platform that builds scalable network applications. It uses an event loop to handle asynchronous I/O operations.
Event Emmiter(Emit Events) -> Event Listener(Call) -> Callback
const eventEmitter = require('events')
const myEmmiter = new eventEmitter()
// listeners
myEmmiter.on('birthday', () => {
console.log('Happy birthday');
})
myEmmiter.on('birthday', (gift) => {
console.log(`Happy birthday ${gift}`)
})
myEmmiter.emit('birthday', 'watch')
Stream and Buffer :
It is used to process data piece by piece which is called buffer.
- It is better in terms of user experience.
- Needs short memory storage as it does not complete the whole process at once.
Different types of streams :
- Readable stream — a steam whee we can read data
- writable stream — a stream where we can write data
- duplex stream — a stream for both write and read
- Transform stream - a stream where can we reshape data
Readable Stream :
const fs = require('fs')
const ourREadStrean = fs.createReadStream(`${__dirname}/read.txt`)
ourREadStrean.on('data', (chunk) => {
console.log(chunk.toString());
})
Writable Stream :
const fs = require('fs')
const writeStream = fs.createWriteStream(`${__dirname}/writeStream.txt`)
writeStream.on('New content', (chunk) => {
writeStream.write(chunk.toString())
})