1. What is Node.js?
Node.js is a JavaScript runtime. It runs JavaScript on the server side, not only in the browser. It uses the Chrome V8 engine.
Full lesson: Nodejs intro
45 questions about Node.js with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.
Node.js is a JavaScript runtime. It runs JavaScript on the server side, not only in the browser. It uses the Chrome V8 engine.
Full lesson: Nodejs intro
Run the node -v command in a terminal. The command prints the installed version.
node -v
Full lesson: Nodejs tutorial
A function is a reusable block of code. It performs one task. Functions help you reuse code and keep programs easy to maintain.
function greet(name) {
console.log(`Hello, ${name}!`);
}
Full lesson: Nodejs function
Call require with the name fs. The require call returns the module object. You can also use the import syntax in ES modules.
const fs = require('fs');
Full lesson: Nodejs fs module
Call url.parse with the URL string. The method returns a URL object. The object holds the protocol, host, path, and query parts.
const url = require('url');
const u = url.parse('https://example.com:8080/a?x=1');
console.log(u.hostname);
Full lesson: Nodejs url module
Call querystring.parse with the query string. The method returns a plain JavaScript object. Each key-value pair becomes one property.
const qs = require('querystring');
console.log(qs.parse('name=John&age=30'));
Full lesson: Nodejs querystring module
Use the path module. The path.sep property holds the separator. It is a backslash on Windows and a slash on Linux.
const path = require('path');
console.log(path.sep);
Full lesson: Nodejs path module
Use the os module. Methods such as os.arch and os.totalmem return system data. The data helps you adapt the program to the platform.
const os = require('os');
console.log(os.arch());
console.log(os.totalmem());
Full lesson: Nodejs os module
Call http.createServer with a request handler. Then call listen on a port. The server sends a response for each request.
const http = require('http');
http.createServer((req, res) => {
res.end('Hello');
}).listen(8080);
Full lesson: Nodejs http module
Call net.createServer with a connection handler. Then call listen on a port. The server runs a callback when a client connects.
const net = require('net');
net.createServer((socket) => {
socket.end('Hello\n');
}).listen(8080);
Full lesson: Nodejs net module
Use npx and the package name. npx downloads the package and runs it. You do not install the package globally.
npx cowsay hello
Full lesson: Npx intro
Use the vm module. Call vm.runInNewContext with the code and a sandbox object. The code runs apart from the main program.
const vm = require('vm');
vm.runInNewContext('x = 1', {});
Full lesson: Nodejs vm module
A common mistake is to use the sync methods in a server. Sync calls block the event loop. Use the async methods or promises instead.
fs.readFile('a.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
Full lesson: Nodejs fs module
A common mistake is to forget res.end. The response stays open and the client waits. Always end the response.
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Done');
}).listen(8080);
Full lesson: Nodejs http module
A common mistake is to ignore the error argument in the callback. A failed lookup returns an error. Always check the error first.
dns.lookup('example.com', (err, address) => {
if (err) return console.error(err.message);
console.log(address);
});
Full lesson: Nodejs dns module
The REPL is an interactive programming environment. It reads, evaluates, prints, and loops code you type.
node
Full lesson: Nodejs repl module
You create an EventEmitter object. You register a listener with the on method and trigger the event with the emit method.
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', () => console.log('Hello'));
emitter.emit('greet');
Full lesson: Nodejs events module
You use the gzip function to compress a buffer. The callback receives the compressed data.
const zlib = require('zlib');
zlib.gzip('Hello World', (err, buffer) => {
if (err) throw err;
console.log(buffer);
});
Full lesson: Nodejs zlib module
You call dgram.createSocket with the type 'udp4'. The socket can send and receive datagrams.
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
socket.send('Hello', 8080, 'localhost');
Full lesson: Nodejs dgram module
You use Buffer.from with the string and an encoding. The default encoding is utf8.
const buf = Buffer.from('Hello', 'utf8');
console.log(buf);
Full lesson: Nodejs buffer module
You use crypto.createHash with the algorithm name. You update the hash with data and get the digest in hex format.
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update('Hello World');
console.log(hash.digest('hex'));
Full lesson: Nodejs crypto module
You use util.format with a format string and arguments. It returns a formatted string.
const util = require('util');
console.log(util.format('%s is %d', 'Alice', 30));
Full lesson: Nodejs util module
You use assert.ok to check if a value is truthy. If the value is falsy, it throws an AssertionError.
const assert = require('assert');
assert.ok(true, 'This passes');
assert.ok(false, 'This fails');
Full lesson: Nodejs assert module
The event loop is a mechanism that handles asynchronous callbacks. It allows Node.js to perform non-blocking I/O operations.
Full lesson: Nodejs event loop
You use http.createServer with a request handler. The server listens on a port and responds to requests.
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World');
});
server.listen(3000);
Full lesson: Nodejs web module
A common mistake is to emit an event before adding a listener. The event is lost and the listener never runs.
const emitter = new EventEmitter();
emitter.emit('greet'); // No listener yet
emitter.on('greet', () => console.log('Hello')); // Never called
Full lesson: Nodejs events module
A common mistake is to use string concatenation for paths. This fails on different operating systems. Use path.join instead.
const path = require('path');
// Wrong: 'folder' + '/' + 'file.txt'
// Right: path.join('folder', 'file.txt')
Full lesson: Nodejs path module
A common mistake is to assume Buffer memory is zero-filled. Buffer.allocUnsafe returns uninitialized memory. Use Buffer.alloc for safety.
const buf = Buffer.alloc(5); // safe, zero-filled
console.log(buf);
Full lesson: Nodejs buffer module
A common mistake is to reuse a hash object after calling digest. The hash is finalized and cannot be updated again. Create a new hash for each operation.
const hash = crypto.createHash('sha256');
hash.update('data');
hash.digest('hex');
// hash.update('more'); // Error
Full lesson: Nodejs crypto module
A common mistake is to use the domain module in new code. The module is deprecated. Use async/await or try/catch instead.
Full lesson: Nodejs domain module
The events module provides the EventEmitter class. This class lets objects create, trigger, and listen to custom events.
const EventEmitter = require('events');
Full lesson: Nodejs events module
Call Buffer.alloc with the number of bytes. The buffer is filled with zeros by default.
const buf = Buffer.alloc(10);
console.log(buf.length); // 10
Full lesson: Nodejs buffer module
Call the toString method on the buffer. You can pass an encoding such as 'utf8'.
const buf = Buffer.from('Hello');
console.log(buf.toString()); // Hello
Full lesson: Nodejs buffer module
Use path.resolve() with no arguments. It returns the absolute path of the current working directory.
const path = require('path');
console.log(path.resolve());
Full lesson: Nodejs path module
Use the path.join method. It joins segments and normalizes the result for the current system.
const path = require('path');
console.log(path.join('folder', 'file.txt'));
Full lesson: Nodejs path module
Call util.inspect on the object. It returns a string that is easy to read.
const util = require('util');
console.log(util.inspect({ a: 1 }));
Full lesson: Nodejs util module
Call dns.lookup with the hostname and a callback. The callback receives an error and the address.
const dns = require('dns');
dns.lookup('example.com', (err, address) => {
console.log(address);
});
Full lesson: Nodejs dns module
Call crypto.createHash with an algorithm name. Then call update with the data and digest to get the result.
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update('Hello');
console.log(hash.digest('hex'));
Full lesson: Nodejs crypto module
Run the node command with no file argument. Node.js starts the REPL and shows a prompt.
node
Full lesson: Nodejs repl module
A common mistake is to use util.inspect output as data. The output is for display only and can change between versions.
Full lesson: Nodejs util module
A common mistake is to forget that zlib methods are asynchronous by default. You must wait for the callback or use the sync version.
const zlib = require('zlib');
zlib.gzip('data', (err, buf) => {
if (err) throw err;
console.log(buf.length);
});
Full lesson: Nodejs zlib module
A common mistake is to ignore the 'error' event on a socket. An unhandled error event stops the process.
const net = require('net');
const server = net.createServer();
server.on('error', (err) => console.error(err));
Full lesson: Nodejs net module
A common mistake is to use assert for user input checks in production. Assertion errors stop the program and are for testing only.
Full lesson: Nodejs assert module
A common mistake is to run untrusted code in a vm context. The vm module does not provide a security sandbox.
Full lesson: Nodejs vm module
A common mistake is to expect nested objects from querystring.parse. The querystring module does not support nested structures.
const qs = require('querystring');
console.log(qs.parse('a=1&b=2')); // { a: '1', b: '2' }
Full lesson: Nodejs querystring module