Node.js is an open-source and cross-platform JavaScript runtime environment. Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser.
Single-threaded, nonblock, asynschronus allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.
From the perspective of a frontend developer who extensively uses JavaScript, Node.js apps bring with them a huge advantage: the comfort of programming everything - the frontend and the backend - in a single language.
You have a huge opportunity because we know how hard it is to fully, deeply learn a programming language, and by using the same language to perform all your work on the web - both on the client and on the server, you're in a unique position of advantage.
In the browser, most of the time what you are doing is interacting with the DOM, or other Web Platform APIs like Cookies. Those do not exist in Node.js, of course. You don't have the document
, window
and all the other objects that are provided by the browser.
Another difference is that Node.js uses the CommonJS module system, while in the browser we are starting to see the ES Modules standard being implemented.
In practice, this means that for the time being you use require()
in Node.js and import
in the browser.
node -v
v14.15.4
Your version might be different, no worries. But if you have no version , please make sure that you follow this guide to install NodeJs
The node command is the one we use to run our Node.js scripts:
node script.js
A Node.js file can import functionality exposed by other Node.js files.
When you want to import something you use
const library = require("./library");
to import the functionality exposed in the library.js
file that resides in the current file folder.
In this file, functionality must be exposed before it can be imported by other files. This is what the module.exports
API offered by the module
system allows us to do.
// in car.js
const car = {
brand: "Ford",
model: "Fiesta",
};
module.exports = car;
//..in the other file
const car = require("./car");
The second way is to add the exported object as a property of exports
. This way allows you to export multiple objects, functions or data:
// in car.js
const car1 = {
brand: "Ford",
model: "Fiesta",
};
const car2 = {
brand: "Kia",
model: "Sorento",
};
exports.car1 = car1;
exports.car2 = car2;
or directly
exports.car1 = {
brand: "Ford",
model: "Fiesta",
};
exports.car2 = {
brand: "Kia",
model: "Sorento",
};
In the other file
const cars = require("./car");
console.log(cars);
// {
// car1: { brand: 'Ford', model: 'Fiesta' },
// car2: { brand: 'Kia', model: 'Sorento' }
// }
Or you can use destructuring
const { car1 } = require("./library");
console.log(car1);
// { brand: 'Ford', model: 'Fiesta' }
|- monday/
|- outer.js
|- layer1/
|- index.js
|- layer2/
|- index.js
|- data.js
|- layer3/
|- index.js
layer1/index.js
export a module that return hello world from layer 1 !
layer2/data.js
export a module that has:data
data
is an array contain 5 objectsname:anyName
and age:anyNumber
layer2/index.js
import data that previously made.layer2/index.js
export a module that when called : print to the console this format:User name is : anyName User age is : anyAge
layer3/index.js
import data from layer2/data.js
layer3/index.js
export a module that contain a method that print to the consoleUser <anyName> is oldest, age <anyAge> User <anyName> is youngest, age <anyAge>
outer.js
import all module and execute in an order that print to the console. You may also have to add in some more command to complete the formatHello world from layer1 ! ------- This is the list of Users : User name is <anyName>, User age is : <anyAge> ======== User <anyName> is oldest, age <anyAge> User <anyName> is youngest, age <anyAge>
Node js offers many useful modules for us to communicate with our machine
const fs = require("fs");
fs.readFile("test.txt", "utf8", (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
readFile is Asynchronous meaning that code below will be executed before readFile
finish. Try console.log outside the method you would receive undefined.
Alternatively, you can use the synchronous version fs.readFileSync()
:
const fs = require("fs");
try {
const data = fs.readFileSync("test.txt", "utf8");
console.log(data);
} catch (err) {
console.error(err);
}
fs.xxSync are Synchronous methods, meaning that the method must be finish before other codes could be run. Try create a global variable myGlobal
and assign to it the value of fs.readFileSync
. Then console.log myGlobal
at the end of script file.
The fs module provides a lot of very useful functionality to access and interact with the file system.
File system method | Effect |
| check if the file exists and Node.js can access it with its permissions |
| append data to a file. If the file does not exist, it's created |
| close a file descriptor |
| copies a file |
| create a new folder |
| read the contents of a directory |
| read the content of a file. Related: |
| rename a file or folder |
| remove a folder |
| write data to a file. Related: |
The path module provides a lot of very useful functionality to access and interact with the file system.
const path = require("path");
Every file in the system has a path. On Linux and macOS, a path might look like:
/users/joe/file.txt
while Windows computers are different, and have a structure such as:
C:\users\joe\file.txt
You need to pay attention when using paths in your applications, as this difference must be taken into account. The path.join()
method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. More details
In reality, we will not commonly embeded data into our js file like the previous exercise.
We would store our data in a separated .json file and import it as needed. This would help other module able to access to the one database , one source of truth.
"data":{
"name":"abc"
}
data: {
name: "abc";
}
db.json
with the data from data.js
in previous exercise at root
of our project structure.layer2/index
and layer3/index
replace the use of data.js
and change to db.json
insteadJson
file format need to be turn to JS
object before usage.... require("fs")
... fs.read... or fs.readSync...
... callBack???
... const data = ...? JSON.parse() ???
The following example creates a web server that listens for any kind of HTTP request on the URL http://127.0.0.1:5000/
— when a request is received, the script will respond with the string: "Hello World".
test-node
. Create a new file called hello.js
:// Load HTTP module
const http = require("http");
// Create some constants help configurate connection
const hostname = "127.0.0.1";
const port = 5000;
// Create HTTP server with http method
const server = http.createServer((req, res) => {
// Set the response HTTP header with HTTP status and Content type
res.writeHead(200, { "Content-Type": "text/plain" });
// Send the response body "Hello World"
res.end("Hello World\n");
});
// Prints a log once the server starts listening
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
node hello.js
The World's Largest Software Registry (Library). They host, stored and distribute more than 800,000 code packages. Open-source solutions, library ,softwares sharing platform. Many organizations also use npm
to manage private development. Another poppular alternateive is yarn
.
root
!npm init
accept all question , enter keys
When starting a npm for your project, a package.json
file will be create. This file is writen in JSON
format. Here lies all your projects infos
{
"name": "project_name",
"version": "project_version",
"description": "project_description",
"main": "root_file",
"scripts": {
"test": "test command run",
"start": "start command run",
"xxx": "xxx command run"
},
"dependencies": {
"library": "library_verison"
},
"author": "author",
"license": "ISC"
}
Required fields:
Importants fields:
package.json
keeping a list of dependencies
name and version so that running the code would only need to use npm install
everything in the list.REMEMEBER: to install dependecies right after clonning, pulling or receiving any code.
npm install
# or
npm i
WARNING: Sometimes, you may encounter instruction to npm i -g ...
. The -g
is a flag that help us to install the software GLOBALLY
. Ask yourself do you need to install this to your entire machine or just simply in the directory for your project. Be vert cautious on what you installing on your machine.
Also npm have many options, the list of them could be find here.
nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.
nodemon does not require any additional changes to your code or method of development. nodemon is a replacement wrapper for node. To use nodemon, replace the word node on the command line when executing your script.
using npm to install nodemon
npm i nodemon
Add new command for scripts
in package.json
so that your machine using nodemon
to execute your code
{
// ...
"scripts":{
// ...
"dev": "nodemon yourStartFile"
}
"dependencies":{
"nodemon":"x.x.x" }
}
Previously : package.json
keeping a list of
dependencies
name and version so that running the code would only need to use
npm install
everything in the list
Yes, but we are missing one important step. To not use git history track for files, softwarem or changes we must specify so to git
. The .gitignore
file contain list of paths to files and folders that you wish not to track history. Thus, not included in your push
to github
or any cloud
root
touch .gitignore
.gitignore
add# node_modules
node_modules/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
Warning : one common mistake is to git init
then npm init
then create .gitignore
. This will not have effect on node_modules/
ignore since the npm init alread make a node module
and the git init before it has track the changes
. You may need to remove the git cache
to fix this issue.
Recommended : Workflow
1. Create folder structure
2. Initialize NPM
3. Install NPM to create `node_modules/`
4. Create `.gitignore` and add `node_modules/` to the list
5. Initialize Git
6. as usual...
If you could finish the bounus, this will be your first full-stack application
But first to build an API , most of the time we will use a library framework to help us start fast and effecient. Most popular one is Express JS
. But that will be a topic for another day another time. For this exercise we will clone this repo and add some work.
Very often in a real job, as a Junior Programmer , one may spend more time reading existing code and add features than coding from 0. Your are assigned to create an API (bonus: Fullstack Web) using the provided codebase. It is important that you read the README.md of any project before start coding
Hey there, travelers! if you want to learn everything about Node that has not been covered (lots of it), check out the links below to have better understanding of the concepts.