Node
date
Sep 1, 2022
type
KnowledgeBase
year
slug
nodejs
status
Published
tags
JavaScript
Node
summary
Everything you need to know to install and use NodeJs (as well as Express.js)
Further reading: 📙 Tiny Node Projects
Installation
Install node from https://nodejs.org/en/
n - Node version manager
Install the n node version manager via
$ sudo npm install -g n
Upgrade to the latest version of node via $ sudo n latest
Options:
Switch to specific version of node:
$ sudo n 10.16.0
Switch to long-term-support version: $ sudo n lts
Switch to newest release: $ sudo n latest
View downloaded versions: $ n
(then up
/down
arrow, return
to install, d
to delete)Start a new Node project
$ npm init
and step through the wizard, name the entry point app.jsCreate app.js and put this in it:
console.log('hello world');
run with
$ node app.js
Automatic updates via Nodemon
If we don’t want to re-run after every change we can install nodemon via
$ npm install -g nodemon
Then start via
$ nodemon app.js
nodemon will now automatically restart whenever it detects file changes!
Project structure
A typical Node web application has the following components:
- package.json—A file that contains a list of dependencies, and the command that runs the application
- public/—A folder of static assets, such as CSS and client-side JavaScript
- node_modules/—The place where the project’s dependencies get installed
- One or more JavaScript files that contains your application code
The application code is often further subdivided as follows:
- app.js or index.js—The code that sets up the application
- models/—Database models
- views/—The templates that are used to render the pages in the application
- controllers/ or routes/—HTTP request handlers
- middleware/—Middleware components
Modules
If we want to
import
modules we need to add "type" : "module"
to our package.json file. We can then add a module (like bcrypt
) to the project via $ npm i bcrypt
and then import it in app.js via import bcrypt from “bcrypt”;
Exit
Quit out of your app at any time via
process.exit();