Hello Everyone,
In this post we will go through an introduction of NodeJS. It is built on Chrome’s V8 JS engine. Basically NodeJS allows us to use JavaScript to build servers and backend applications.
NodeJS is a JavaScript run time environment. It is the way to run JavaScript outside the browser.
Differences between browser and node.js environment.
Globals in NodeJS
In NodeJS there is no window, because there is no browser, so there is no window object.
But there are global variables, and here are some most commonly used global variables in NodeJS.
- __dirname: Path to current directory.
- __filename: file name.
- require: function to use modules (CommonJS).
- module: info about current module (file).
- process: info about env where the program is being executed.
Modules are just separated scripts and files, there are several built in modules in NodeJS. Let’s cover the most popular ones.
- OS module
- PATH module
- FS module
- HTTP module
OS Module
OS module provides information about the operating system. Here are some examples.
1const os = require('os');23const currentOS = {4 userInfo: os.userInfo(),5 name: os.type(),6 release: os.release(),7 totalMem: os.totalmem(),8 freeMem: os.freemem(),9}1011console.log(currentOS);
Path Module
Path module provides functions and information for the file paths.
1const require("path");23console.log(path.sep);4// consoles the folder separator ("/").56const filePath = path.join("/content", "subfolder", "test.txt");7// Joins the path of the given folder and files ("/content/subfolder/test.txt").89const base = path.basename(filePath);10// Gives the base of the given file path.1112const absolutePath = path.resolve(__dirname, "content", "subfolder", "test.txt");13// This joins and returns the absolute file path.
FS Module
FS module provides functions and info about the file system. This mainly helps us to read and write files.
There are two ways to use FS module:
- Sync: Reads and writes the file synchronously.
- Async: Reads and writes the file asynchronously using callbacks.
1/* Sync Example */2const { readFileSync, writeFileSync } = require("fs");34const fileContent = readFileSync("./content/first.txt", "utf8");5console.log(fileContent); // consoles the content of given file.6// readFileSync reads the content of the given file synchronously.78writeFileSync(9 "./content/result-sync.txt",10 `Here is the result: ${fileContent}`11);12// writeFileSync writes the given content to the given file. And creates the file if it does not exists.1314/* Async Example */15const { readFile, writeFile } = require("fs");1617readFile("./content/first.txt", "utf8", (err, result) => {18 if (err) {19 console.log(err);20 return;21 }22 console.log(result);23});2425writeFile(26 "./content/result-sync.txt",27 `Here is the result: ${fileContent}`,28 (err, result) => {29 if (err) {30 console.log(err);31 return;32 }33 console.log(result);34 }35);
HTTP Module
This module let’s us make Http request in NodeJS to transfer data over Http. HTTP module creates an HTTP server that listens to server ports and gives a response back to the client.
1const http = require('http')23const server = http.createServer((req, res) => {4 if (req.url === '/') {5 res.end('Welcome to our home page')6 } else if (req.url === '/about') {7 res.end('Here is our short history')8 } else {9 res.end(`10 <h1>Oops!</h1>11 <p>We can't seem to find the page you are looking for</p>12 <a href="/">back home</a>13 `)14 }15})1617server.listen(5000)
NodeJS Event Loop
With help of event loop we can offload some time consuming operations.
The event loop is what allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible.
For example without the event loop if a user requests for a time consuming operation, other users will be blocked till the operation is completed.
And with the event loop, the operation is offloaded and executed only when completed, hence other users are not blocked.
More detail on NodeJS event loop: https://nodejs.dev/learn/the-nodejs-event-loop
1const { readFile, writeFile } = require('fs');23console.log('started first task');4// CHECK FILE PATH!!!!5readFile('./content/first.txt', 'utf8', (err, result) => {6 if (err) {7 console.log(err);8 return9 }10 // console.log(result)11 console.log('completed first task')12})13console.log('starting next task');1415// Result:16// started first task17// starting next task18// completed first task
Event-driven programming
In event-driven programming, we listen for specific events and register functions that will execute in response to those events. So, once our event takes place callback function fires.
Event objects have many methods, the two most used are:
- on: listen for an event.
- emit: emit an event.
1const EventEmitter = require("events");23const customEmitter = new EventEmitter();45customEmitter.on("response", (name, id) => {6 console.log(`data recieved: ${name} with id: ${id}`);7});89customEmitter.emit("response", "john", 34);
A bunch of built-in modules rely heavily on this concept of events.
Streams
In NodeJS streams are used to read and write sequentially. Streams help us handle and manipulate streaming data, for example, continuous source or a big file stream.
There are four types of streams:
- Writeable: To write data sequentially.
- Readable: To read data sequentially.
- Duplex: To both read and write data sequentially.
- Transform: To modify data while reading or writing.
1const { createReadStream } = require('fs')23// default 64kb4// last buffer - remainder5// highWaterMark - control size6// const stream = createReadStream('./content/big.txt', { highWaterMark: 90000 })7// const stream = createReadStream('../content/big.txt', { encoding: 'utf8' })8const stream = createReadStream('./content/big.txt')910stream.on('data', (result) => {11 console.log(result)12})13stream.on('error', (err) => console.log(err))
HTTP stream example.
1const http = require("http");2const fs = require("fs");34http.createServer(function(req, res) {5 // const text = fs.readFileSync('./content/big.txt', 'utf8')6 // res.end(text)78 const fileStream = fs.createReadStream("./content/big.txt", "utf8");9 fileStream.on("open", () => {10 fileStream.pipe(res);11 })12 fileStream.on("error", (err) => {13 res.end(err);14 })15}).listen(5000);
Basic NodeJS server app setup.
Here is a basic server setup with core NodeJS.
1const http = require('http')2const { readFileSync } = require('fs')34// get all files5const homePage = readFileSync('./navbar-app/index.html')6const homeStyles = readFileSync('./navbar-app/styles.css')7const homeImage = readFileSync('./navbar-app/logo.svg')8const homeLogic = readFileSync('./navbar-app/browser-app.js')910const server = http.createServer((req, res) => {11 // console.log(req.method)12 const url = req.url13 console.log(url)14 // home page15 if (url === '/') {16 res.writeHead(200, { 'content-type': 'text/html' })17 res.write(homePage)18 res.end()19 }20 // about page21 else if (url === '/about') {22 res.writeHead(200, { 'content-type': 'text/html' })23 res.write('<h1>about page</h1>')24 res.end()25 }26 // styles27 else if (url === '/styles.css') {28 res.writeHead(200, { 'content-type': 'text/css' })29 res.write(homeStyles)30 res.end()31 }32 // image/logo33 else if (url === '/logo.svg') {34 res.writeHead(200, { 'content-type': 'image/svg+xml' })35 res.write(homeImage)36 res.end()37 }38 // logic39 else if (url === '/browser-app.js') {40 res.writeHead(200, { 'content-type': 'text/javascript' })41 res.write(homeLogic)42 res.end()43 }44 // 40445 else {46 res.writeHead(404, { 'content-type': 'text/html' })47 res.write('<h1>page not found</h1>')48 res.end()49 }50})5152server.listen(5000)
That’s it for the basics of core NodeJS. If you found this helpful, please do share and subscribe to my newsletter below or here.
Thank You!