[NEM] 01 - Intro to NodeJS and NPM
NodeJS
- a JS runtime
- built on Google’s open-source V8 JS engine
- used to isolate JS from the client-side’s browser runtime
- V8 engine runs the code on the server
- making NodeJS a perfect web server
- allows JS to be used as a server-side language
- to build fast and highly scalable back-end network applications
Notable Characteristics
- single-threaded, event-driven, non-blocking I/O model
- makes NodeJS lightweight and efficient
- allows for using JS throughout the stack
- Node Package Manager (NPM): huge open-source packages for NodeJS available
- good for building fast and scalable data-intensive applications
Applications
- API with database
- Data Streaming like YouTube
- Real-Time Chat applications
-
Server-Side Web Applications
- do not use NodeJS for heavy server-side processing
- video conversions
- file compressions
- heavy image manipulation
- for heavy server-side processing, use
- Ruby
- Python
- PHP
Well-know Users of NodeJS
- Netflix
- UBER
- PayPal
- ebay
NodeJS Setup
- Setup an isolated NodeJS development docker container using this tutorial
- Clone this template GitHub repo to get started with Docker development container
Node REPL
- REPL: Read-Eval-Print-Loop
- the internal CLI of node
- enter
node
in CLI after installing NodeJS on your system
- javascript code can be run like in a CLI-based based environment
- like IPython for instance
Sync vs. Async Code
- synchronous code is also called blocking code
- doesn’t execute the next command or line in script until current line completes execution
- certain operations don’t execute unless the previous code has completed
- asynchronous code is written to avoid this blocking
- the future lines of code will be executed while current asynchronous code waits for execution to complete
Callback functions
- these are an important part of asynchronous functions
- callback functions are triggered at the end of execution of async function
- using callbacks doesn’t automatically make a function asynchronous
- only certain function have the callback functionality
Need for Asynchronous Code
- NodeJS is single threaded
- irrespective of whether 5 people are accessing the backend server or 5 million
- so if millions of users are running synchronous code, the single thread is blocked to run the user requests in a queue
- this would delay the response for all users
- async code comes to the rescue in these situations
- it is the responsibility of the NodeJS programmer to write asynchronous code to handle multiple users that scale up to millions
- time consuming tasks must be made asynchronous functions to allow other faster requests to go through
- callbacks can be used to automatically execute after the asynchronous function has completed execution