Back-End Development and APIs Certification (freeCodeCamp)
Notebook
Own Learning
-
Debug shows in Debug Console and not in terminal
Since Node.js is writing console.log the debut output will be actually in DEBUG CONSOLE in VS Code and not Terminal unless you run in terminal with
node file.js.
Introduction to Node.js
- Client-side JavaScript(JS) limitations: restricted access to local files, not for handling complex application logic, security concerns.
The reason is because it was designed to run exclusively on web browsers. - Web browser provide the environment that is needed to run JS code, including JS engine and provide access to DOM so you can access HTML elements in your code.
- We can run JS outside of browser with Node.js .
- Node.js: Open-source and class-platform JS runtime environment which means:
- Node.js is used to build web servers and APIs that handle HTTP requests, as well as web and mobile applications.
Browser Node runtime environment Primarily for front-end web development so it runs client-side JS. Primarily designed for back-end web development, so it runs server-side JS. From browser you can access the DOM API but there are restrictions for accessing the local file system. You can access almost all system resources including file system, but not the DOM. Global object is called windowwhich provides access to browser-related functionalities, such as access toGlobal object is called globalwhich provides access to Node.js specific functionalities.No control over the browser environment that your users will use to visit your site. You can chose which node.js version to run. - Node.js has become very important for developers worldwide. It has allowed users to use JS both in front-end and back-end of full-stack applications.
This has made the development process more efficient since developers don't need to learn a new programming language just for developing back-end. - Learning Node.js means you can use JS both in front-end and back-end of web applications.
This means your team doesn't have to switch between languages and they can be more productive and efficient. - Node's architecture is non-blocking, event-driven architecture that is great for developing real-time applications, where responsiveness and efficiency are essential for creating a good user experience.
- Node's architecture relies on a single thread and even loop which means it runs one piece of code at a time.
Node's architecture relies of multi-threading. - Node has a large number of community around the world and hence there are a lot of learning resource available.
npmis Node.js's package manager. It is a powerful tool that allows you to install and manage package and modules for your projects.- By using packages you can reuse code that was already written, tested, and shared by other developers to make your workflow faster and more efficient.
- Node.js is free and open source.
- Disadvantages of node:
- Single threaded and so CPU intensive tasks may block the main thread and result in performance issues. For example, complex mathematical operations, image and video processing, cryptography.
- In asynchronous programming, a task that may take a long time to run is started, but instead of waiting until it's completed, the main program continues running while the asynchronous task runs in the background.
This often involves what we now know as "callbacks", which are functions that define what happens when the asynchronous operations are completed.
The asynchronous nature of Node.js can potentially make the code more difficult to read, understand, and debug. - Careful when choosing packages from
npmbecause some of them may not be constantly maintained, so they may introduce vulnerabilities into your own application.
- Node.js is currently one of the most popular tools for developing web applications. Knowing its advantages and disadvantages will help you to determine if it's the right tool for your project.
- NVM(Node Version Manager) is recommended way to install Node.
- Notice the --lts flag. This flag indicates that you want to install the current Long-Term Support (LTS) version of Node.js. This version is usually recommended because it prioritizes stability, reliability, and security over new or experimental features. It is thoroughly tested and ready for production. It's also guaranteed to have longer support periods with a focus on bug fixes and security patches.
nvm install ltsto install the Long-term support version of nvm.nvm use 20to use the version 20 of node.nvm lsto list all the installed version of node.nvm alias default <version>to set the default version of Node.js on Linux/macOS onlynvm alias <new_name> <version>to give a more specific name to a version.
Note: Probably also only on Mac and Linux.npminstalls with node and is the package manager.- To run a JavaScript file,
node <file.js> npm initto create a Node.js project.npm init --yesto start with a defaultpackage.json.npm install <package>to install a specific package.npm installto simply install all the dependencies listed inpackage.jsonnode -e "console.log()will print to console.node -p ""evaluates the expression just like console.log above.- Use
echoto create a file:echo "console.log('Hello from a file')" > hello.js - Node can check the file for syntax errors without actually running the file with:
node --check fileName.js - Node.js also includes and interactive shell called the REPL - it reads an expression you type, evaluates it, prints the result, and loops back for the next input.
You can start REPL withnode - In REPL,
_holds the result of last evaluated expression. - REPL has special commands that starts with a dot
.. Type.helpto see all of them. - To leave REPL type
.exitor Ctrl+D. - There are two ways to import modules in Node, the classic CommonJS style is
require()while the ESM, the modernimport/exportsyntax. - On Windows, Powershell's default execution policy is restricted. Here's how to check and fix that:
Get-ExecutionPolicy
Set-ExecutionPolicy RemoteSigned
- Basic commands of NVM
Node.js Core Modules
- Node.js:
fs(file system module) to work with files and folders. fsis a standard Node.js module so it's available immediately. You just have to import it:const fs = require("fs");fsmodule works both synchronously(sync) and asynchronously(async).fs.writeFile() // Asynchronous file writing fs.writeFileSync() // Synchronous file writing fs.readFile() // Asynchronous file reading fs.readFileSync() // Synchronous file reading fs.open() // Opens a file fs.openAsBlob() // Opens as blob fs.openSync() // Synchronous open fs.opendir() // Opens directory fs.opendirSync() // Synchronous directory open- And you can use the methods in three ways:
- with callbacks:
fs.writeFile()(async) - with promises if you prefer the
async/awaitsyntax:fs.promises.writeFile() - sync:
fs.writeFileSync()
- with callbacks:
- Basic syntax of async usage of methods:
//async fs.writeFile("filePath", "content", "utf8", (err) => { if (err) { throw err; } console.log("File written to!"); }); //promises async function promisesExample() { try { await fs.promises.writeFile("filePath", "content", "utf8"); console.log("File written to!"); } catch (err) { console.error("Error:", err); } } promisesExample(); // sync try { fs.writeFileSync("filePath", "content", "utf8"); console.log("File written to!"); } catch (err) { console.error("Error:", err); } - Synch methods blocks: The program will stop running and wait until the operation is finished before moving on to the next line of code.
- For small projects, sync methods are fine but in real world applications, syn freezes other parts of your app. Async solves that problem but they traditionally used callbacks which can get messy with scale.
Promises andasync/awaitsolve that problem. The are still non-blocking, but the code reads like a normal sync code and is much easier to maintain. writeFile()writes to an existing file or creates one to write to it NOT APPENDS.:const fs = require("fs/promises"); async function writeToFile() { try { await fs.writeFile( "article.md", "## Node `fs` Module: The Complete Guide", "utf8", ); console.log("File written to!"); } catch (err) { console.error("Error writing to file:", err); } } writeToFile(); // File written to!- The
appendFile()method lets you append to an existing file. readFile()method lets you read the contents of a file at once.
If you don't specify character encoding, you will get the contents of a file as buffer.unlink()method lets you delete a file.- JS was originally created to run in web browsers to make web interactive so early JS focussed on handling text in DOM.
- Files, images, videos are binary data which require different handling mechanism by specialized components of the browser rather than by JS itself.
- Modern browsers use rendering engines and JS engines to manage these tasks:
- Chrome: Blink(with V8)
- Safari: WebKit (with JS Core).
- Gecko: Gecko (with SpiderMonkey)
- Node.js does not run in browser hence it needs it's won way to handle binary data: when handling IO and TCP streams(data coming in chunks).
- The Node.js
Buffermodule lets you work with binary data like files, images, or network streams directly. With it, you can store and manipulate binaries directly in memory. - To use buffer import the module first by destructing:
const { Buffer } = require("buffer"); - Here's a way to cal it:
// Create a buffer from a string const myStrBuffer = Buffer.from("freeCodeCamp"); console.log(myStrBuffer); // <Buffer 66 72 65 65 43 6f 64 65 43 61 6d 70> // Create a buffer from an array of numbers const myNumBuffer = Buffer.from([ 70, 82, 69, 69, 67, 79, 68, 69, 67, 65, 77, 80, ]); console.log(myNumBuffer); // <Buffer 46 52 45 45 43 4f 44 45 43 41 4d 50> - Always import buffer as not all methods of buffer are available without it.
bufferelements can be accessed just like an array.Buffer.from()lets you create a buffer from a string, array or, other raw data.Buffer.alloc()lets you create a new buffer of a given size(number of bytes). Every byte inside it is automatically filled with0.toString()let's you convert buffer to a string.- If you write more data than the buffer can hold, the data will be truncated.
Buffer.byteLength()to show the number of bytes needed to store a string in a certain encoding:console.log(Buffer.byteLength("Hello freeCodeCamp")); // 18Buffer.isBuffer()checks if an object is buffer.Buffer.compare()compares two buffers and returns their sort order.Buffer.concat()joins multiple buffers together into one.- Crypt module contains stuff for security.
- Crypt module contains low-level building blocks, not plug-and-play security.
- Instead of writing your own encryption, it's best to use well-tested libraries like
bcryptfor password hashing andjsonwebtoken(JWT) for handling logins and tokens. - Import crypt module with
const crypto = require("crypto");