This repository is based on 40+ hours complete Node.js course by Academind including tools to work with node.js from basic to advanced.
A tool to add external packages and manage nodejs apps.
To add custom scripts to make dev workflow easier there are two ways:
- Script with reserved word: run with
npm <script_name>
e.g.npm start
- Your own custom script name: run with
npm run <script_name>
e.g.npm run my-script-name
If project is new and node_modules
folder not included: npm install
initializes the project.
Adding new package - Three options: a) Global (all projects): npm install -g b) Dev only (not needed in prod): npm install --save-dev c) Prod only: npm install --save
Enables "hot reloading" so you don't have to restart the server everry time you make a change in your code
Init express server
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const app = express()
app.use(bodyparser.urlencoded({extended: false})
app.use()
(All http methods)app.get()
(Only GET)app.post()
(Only POST)
if you want to expose client to some files (e.g. CSS) in your node.js app, you have to put them into public folder
NOTE: when referring to public folder, use "/" as route, not "/public/" as node sees public files are in the root
Tools to mix dynamic content (JS) into template (HTML). The final page response will be always pure HTML. Define template engines with express using app.set("view engine", "handlebars")
and return template by res.render(...)
.
No end tags, indentation important
main
if prods.length > 0
...
else
...
Variable
title #{pageTitle}
Can extract main layout by
extends layouts/main-layout.pug
Uses {{...}} to separate JS, uses #
to start and /
to end. Can extract main layout into separate file
<main>
{{#if hasProducts }}
...
{{ else }}
...
{{/if }}
</main>
Variable
<title>{{ pageTitle }}</title>
Can extract main layout into main-layout.handlebars
and define in app.js
(not in template)
app.engine(
"handlebars",
expressHbs({
layoutsDir: "views/layouts",
defaultLayout: "main-layout",
extname: "handlebars"
})
);
You must define body (where content goes) in main-layout.handlebars
template:
{{{ body }}}
JS wrapped inside <% ... %>
.
<main>
<% if (prods.length > 0) { %>
...
<% } else { %>
...
<% } %>
</main>
Variable
<title><%= pageTitle %></title>
Can extract main layout into separate files (head.ejs
, navigation.ejs
, end.js
), import into template by
<%- include('includes/head.ejs') %>