Check out our Coding
Classes
These slides are for the webinar: Intro to Node.js
Before we talk about what Node.js is, we need to exam how JavaScript works on the browser/client side.
Almost all modern browsers have JavaScript engined baked into the browser. This is why we can run JavaScript in the browser.
In 2008, Google released their Chrome web browser using the Google V8 engine.
In 2009, Ryan Dahl used the Google V8 Engine to run JavaScript without using a browser.
This gave birth to Node.js. It allows us to create a server, read files, send messages, access a database, and much more.
Traditionally, languages such as PHP, Ruby, and many similar programming languages require a lot of resources to handle multiple requests.
Think of a restaurant hiring multiple workers when it gets very busy. The only problem is what to do with the extra workers when the restaurant is slow.
On the other hand, Node.js works completely opposite.
It doesn’t hire additional workers to meet the demand, but it has a task manager that distribute the tasks smartly.
This way, you don’t need to hire additional workers and also get the job down efficiently.
JavaScript, by itself, is a synchronous language.
But when JavaScript is run on the browser or on the server, it becomes an asynchronous language.
Application Programming Interface
Think of the API as a smoothie shop menu. The drink menu shows a collection of drinks you can order and the ingredients. You can order it and customize it however you see fit.
An example of an API is Airbnb: You browse a list of homes you want to stay in for your vacation. You can pick a dog-friendly home with a parking space. An API could be a list of features or a pile of data.
The browser API allows coder to manipulate the DOM.
Think of following or unfollowing a friend on Instagram.
It shows you that you have 1 follower, and if you don’t have any it will show you have 0 followers.
The Node API allows programmers to start a server, read files, access databases, password hashing, and more.
Under the hood, when the Google V8 engine reads the JavaScript files, and it sees them trying to read a file, it will access the LIBUV library and use the read file function.
Which is why Node.js is allowed to start a server.
LIBUV is written in C and C++.
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
No SQL database, it uses the document object model
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});