Introduction to Node.js
- JavaScript outside of a browser
- You can build...
- Console applications
- Scalable network applications
- Fast and robust
- Single-threaded (child processes are possible)
- Non-blocking
- Well suited for web development
- Not well suited for CPU-intensive applications
- 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.
<!--#include file="node-fundamentals/0010-hello-world-console/app.js" -->
- Run it with:
node app.js
- Note template string
<!--#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
<!--#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
<!--#include file="node-fundamentals/0030-file-system/app.js" -->
More about core modules fs and process
What is the output of this program?
<!--#include file="excursus/0020-truthy-falsy/app.js" -->
Timers and Intervals (1/2)
<!--#include file="node-fundamentals/0050-timers/timeout.js" -->
- Try adding the line
console.log('End of program');
at the end - Discuss the result
Timers and Intervals (2/2)
<!--#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" -->
- Want to know more? Read/watch...
- Node.js built-in API
- First two lessons of Einführung in Node.js (German)
- Exercises