Three examples of interactions between an app’s frontend and backend such as:
Thanks Phillip!
Node doesn’t pause for things to complete, it keeps running other processes when events take place, it is NON-BLOCKING EVENT-DRIVEN
Other programming languages have to have multiple threads to handle this type of concurrency but Node is single-threaded and uses its event loop to manage
YAY CALLBACKS
Node does things asynchronously. V8 does not. (JS is also synchronous, but we have tricks!)
You will also install npm as you install node.js!
> var string = 'hello';
> string
'hello'
> string + ' world'
'hello world'
In a REPL, the user enters one or more expressions and the REPL evaluates them and displays the results.
How would you test a boolean in Node's REPL?
Let's write your first Node.js program. Create a new folder called "Node_Practice". Inside that directory make a new file called main.js. Place this code inside.
console.log('Hello World!');
Save that file by clicking command+s and go to your Terminal in your IDE. Type in the following and hit enter.
node main.js
You just executed your first node.js program. Now for the cool stuff.
Add a new file in your Node_Practice directory called 'dinosaurs.txt'. Copy this list of awesome dinosaurs and paste it in your file.
Go back to your main.js file.
var fs = require('fs');
var cwd = process.cwd();
fs.readFile(cwd + '/dinosaurs.txt', function(err, data) {
console.log(data.toString());
});
Now go to your Terminal and run it:
node main.js
We used a module to pull in code, read an external text file, and converted the contents of that file from a Buffer to a string
A module is a JavaScript library/file that you can import into other code using Node's require() function.
The require function is part of CommonJS.
Node has three sources of modules
You can do require for a sub-folder require(“./other/foo”) as well as up and over require(“../lib/over”)
GREET EXAMPLE
You will want to create your own modules, because this allows you to organise your code into managable parts — a monolithic single-file application is hard to understand and maintain.
Using modules also helps you manage your namespace, because only the variables you explicitly export are imported when you use a module.
You can do module.export multiple times in the same file
Resources
ES6 has a new way of creating modules in JavaScript, this is something that most languages has but JS has not taken advantage of until now.
ES6 modules have the same principle (ie having code in modules and then letting certain parts be accessed)
This hasn't been added into Node yet, but peeps are working on it
Now let's turn the text into an array:
var fs = require('fs');
var cwd = process.cwd();
fs.readFile(cwd + '/dinosaurs.txt', function(err, data) {
var data = data.toString().split('\n');
console.log(data[0]);
});
And run the program again.
Try removing '.toString()' from that line and running the program again.
A buffer is a temporary holding spot for data being moved from place to another. Enough data has to be collected in order to perform a specific process with it (like buffering a video!).
JS can work with Unicode but it isn't too great with binary data. When dealing with TCP streams (moving files across the Internet) or the file system, it's necessary to handle octet streams (binary data flow).
Node has several strategies for manipulating, creating, and consuming octet streams.
Raw data is stored in instances of the Buffer class.
What we care about is that a Buffer is a byte array that can be converted to a human-readable string by adding .toString()
ES6 is adding some new features to make this a bit easier. Stay tuned!
In your main.js file, change 'dinosaurs.txt' to 'people.json' and paste the json from here:
We can use the same fs.readFile function to read JSON. Remember we need to convert the Buffer to a string. This time we'll also parse that string back into JSON.
fs.readFile(cwd + '/curriculum/class1/people.json', function(err, data) {
var data = JSON.parse(data.toString());
console.log(data);
});
Now use your Javascript knowledge to select individual people in the object.
data.people
data.people[0]
Have your program return the eye color of the person at the 3rd index.
We're going to use node's http module to create a server. Create a new file called server.js
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!\n');
}).listen(9000);
console.log('Server running on port 9000');
Now run your progam again and in your browser navigate to localhost:9000
You just wrote your first web app! Node is launching a web server locally. You now have a web server running on your computer.
Information about what is being transmitted and what type of information(MIME type)
MIME stands for Multipurpose Internet Mail Extensions. Read more here
Ports are used to route web traffic. You can use them for all kinds of tasks.
For dev purposes, try to keep it over 1000.
A port and an IP together make a web socket. Sockets can be left open or closed.
In the browser, the JS event loop is constantly listening with its event loop (for when events are triggered in the DOM)
The same happens in Node! There are listeners (like http requests or internal events, responding to a request)
Allow changes without having to stop and restart server
npm install -g nodemon
Run nodemon main.js and try making changes!
This exercise combines using an HTTP server and reading files. The goal is for your server to respond with the contents of a file.
Utility for downloading packages for Node.js applications
Can use to install front-end code, add dependencies, and build tools too!
Difference between a module and a package?
A module is a single JS file that has some functionality and won’t impact other code in the rest of the application unintentionally.
A package is a directory with one or more modules inside of it and a package.json file that has information about the modules inside
Finding a project online or collaborating
Clone this repo, install npm, and start the npm scripts
Starting your own project
npm install vaca --save
const vaca = require('vaca');
console.log(vaca());
node index.js
A global package allows that package to be able to create commands that can be used in the command line (like yarn or grunt or gulp. It can be used across your projectson your computer.
Command for seeing the global packages on your computer: npm list -g --depth 0
Create a package.json file for the Node_practice project we worked on
There is a structure to how developers keep track of the iterations of a package or dependency
Example: 1.8.3
Navigate to your Node_Practice directory and type npm install express (this is NOT global)
Check out your node_modules folder in VSCode
var express = require('express');
var app = express();
app.get('/hello.txt', function(req, res){
res.send("Hello World");
})
var server = app.listen(8080, function() {
console.log('Listening on port 8080');
})
Express makes it really easy to have routes on your webserver (like to your homepage or about page, etc)
So, you can have a lot of gets (and posts) for the different pages on your site.
Create another get that sends a message to someone using your app in another page.
The HTML, CSS, JS, fonts, and images of your website/web app are static assets because they are not changed. They live on your server and need to be sent exactly as they are saved.
This is done over a "public" directory so you don't have to send each item individually. Thanks Express!
You don't want your server -side assets to be public, just your static assets.
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
var server = app.listen(8080);
Git clone this repository, and cd into the node_exercises/static_assets folder
Make sure you understand the code, install express, and run the app!
Check out the Network tab in the Dev tools
Sometimes we need to be able to change the content of a page without having to create an entirely new page.
IMDB example
var express = require('express');
var app = express();
app.get('/celebrity/:name', function(req,res){
res.setHeader('Content-Type', 'text/plain');
res.send("You picked " + req.params.name);
});
var server = app.listen(8080);
Check out node_exercises/posting folder. Run npm install and look at all the code
Body-parser? Express itself does not understand JSON because it remains flexible to understand other languages (like XML). So this parser gives Express the tools to understand JSON.
Check out the final project app in the code you cloned
Watch This Node Module in the Web Developer Course!Click here for Node Documentation