Skip to content

Latest commit

 

History

History
153 lines (109 loc) · 4.81 KB

node-fundamentals.md

File metadata and controls

153 lines (109 loc) · 4.81 KB

Node.js Fundamentals

Introduction to Node.js

What is Node.js?

  • JavaScript outside of a browser
  • You can build...
    • Console applications
    • Scalable network applications
  • Fast and robust
  • Well suited for web development
  • Not well suited for CPU-intensive applications

Working with Node.js

  • Install a good editor (e.g. Visual Studio Code)
  • Install Node.js
    • LTS (long-term support) if stability is very important
    • Current version if you want latest features
  • Write code (e.g. app.js)
  • Run code with node app.js

Note that there are better ways (existing packages on NPM) to implement some features of the following samples. However, we want to learn about Node.js fundamentals, so we use more low-level APIs.

Basic Console App

<!--#include file="node-fundamentals/0010-hello-world-console/app.js" -->

I/O with Console and Readline

<!--#include file="node-fundamentals/0040-console-readline/app.js" -->
  • Note how callback is used to process input from stdin
  • Run this program with node app.js
  • Try node app.js 2> /dev/null (NUL on Windows)
  • Try echo Rainer | node app.js

Basic Web API

<!--#include file="node-fundamentals/0020-hello-world-server/app.js" -->

More about core module http

Excursus: Arrow Functions

<!--#include file="excursus/0010-arrow-functions/app.js" -->

Excursus: JSON

  • Lightweight data-interchange format
  • Easy to read and write
  • Familiar to people knowing C-family of languages
  • Implemented in all major programming platforms

Basic File System Operations

<!--#include file="node-fundamentals/0030-file-system/app.js" -->

More about core modules fs and process

Excursus: truthy and falsy

What is the output of this program?

<!--#include file="excursus/0020-truthy-falsy/app.js" -->
<!--#include file="node-fundamentals/0050-timers/timeout.js" -->
  • Try adding the line console.log('End of program'); at the end
  • Discuss the result
<!--#include file="node-fundamentals/0050-timers/interval.js" -->

Modules (1/2)

  • In Node.js, each file is a separate module
  • Import modules using require
  • Export members from a module using exports
  • Use __filename to get path and file name of a module
  • Use __dirname to get path of a module

Modules (2/2)

math.js:

<!--#include file="node-fundamentals/0060-modules/math.js" -->

app.js:

<!--#include file="node-fundamentals/0060-modules/app.js" -->

Further Readings and Exercises