Node.js143 exercises

Node.js Exercises with Answers

Practise Node.js with 143 interactive exercises: multiple choice, fill-in-the-blank, output prediction and debugging. Every exercise gives instant feedback, a hint and the full solution.

Score0/ 143

1Introduction

Read the lesson
Fill in the blankseasyIntroduction

Complete the command that runs a file called app.js.

 app.js
Multiple choiceeasyIntroduction

Which engine does Node.js use to run JavaScript?

Predict the outputmediumIntroduction

What does this print?

setTimeout(() => console.log('A'), 0);
console.log('B');
Multiple choicemediumIntroduction

Which of these doesn't exist in Node.js by default?

Multiple choicehardIntroduction

Why can one Node process handle many connections at once?

Fill in the blankseasyModules

Complete the line to share the function with other modules.

 function add(a, b) {
  return a + b;
}
Multiple choiceeasyModules

How do you import a default export called formatDate from './dates.js'?

Multiple choicemediumModules

Which setting makes .js files in a project ES modules?

Predict the outputmediumModules

A module contains console.log('loaded') at the top level. Two other files import it in the same program. How many times is "loaded" printed?

Multiple choicehardModules

What replaces __dirname in an ES module?

3npm & Packages

Read the lesson
Fill in the blankseasynpm & Packages

Complete the command that runs the "dev" script.

npm  dev
Multiple choiceeasynpm & Packages

Which file lists a project's dependencies and scripts?

Multiple choicemediumnpm & Packages

Which versions does "^2.4.1" allow?

Multiple choicemediumnpm & Packages

Where should a test runner such as Vitest be installed?

Multiple choicehardnpm & Packages

Why use npm ci instead of npm install in continuous integration?

4File System

Read the lesson
Fill in the blankseasyFile System

Complete the line to read the file as text.

const text = await readFile('poem.txt', '');
Multiple choiceeasyFile System

Which import gives you promise-based file functions?

Multiple choicemediumFile System

What does the error code ENOENT mean?

Predict the outputmediumFile System

What does this print?

await writeFile('a.txt', 'one');
await writeFile('a.txt', 'two');
console.log(await readFile('a.txt', 'utf8'));
Multiple choicehardFile System

Why avoid readFileSync in a web server's request handler?

Fill in the blankseasypath & os

Complete the line to combine the folder and file name.

const file = path.('data', 'users.json');
Predict the outputeasypath & os

What does this print?

console.log(path.extname('photo.backup.png'));
Multiple choicemediumpath & os

What's the difference between path.join and path.resolve?

Predict the outputmediumpath & os

What does this print?

console.log(path.posix.join('/app/src', '..', 'public', 'index.html'));
Multiple choicehardpath & os

Why use path.basename on a file name submitted by a user?

Fill in the blankseasyEvents

Complete the line to trigger the 'saved' event.

store.('saved', { id: 7 });
Multiple choiceeasyEvents

Which module provides EventEmitter?

Predict the outputmediumEvents

What does this print?

const e = new EventEmitter();
e.once('hi', () => console.log('hello'));
e.emit('hi');
e.emit('hi');
Multiple choicemediumEvents

What happens if 'error' is emitted with no error listener?

Multiple choicehardEvents

Are EventEmitter listeners called synchronously or asynchronously?

7process & env

Read the lesson
Fill in the blankseasyprocess & env

Complete the line to read the PORT environment variable.

const port = Number(process..PORT ?? 3000);
Multiple choiceeasyprocess & env

What type are values in process.env?

Predict the outputmediumprocess & env

The program is run with node app.js report.csv 5. What does this print?

console.log(process.argv.slice(2).length);
Multiple choicemediumprocess & env

Which exit code means success?

Multiple choicehardprocess & env

Why listen for SIGTERM in a server?

8Async Patterns

Read the lesson
Fill in the blankseasyAsync Patterns

Complete the line so the function waits for the result.

const user =  findUser(42);
Multiple choiceeasyAsync Patterns

What does an async function always return?

Predict the outputmediumAsync Patterns

What does this print?

async function f() { return 5; }
console.log(f() instanceof Promise);
Multiple choicemediumAsync Patterns

What does Promise.all do if one of its promises rejects?

Multiple choicehardAsync Patterns

Why process a list of 10,000 API calls in batches rather than with one Promise.all?

9HTTP Server

Read the lesson
Fill in the blankseasyHTTP Server

Complete the line to finish the response.

res.writeHead(200, { 'Content-Type': 'text/plain' });
res.('OK');
Multiple choiceeasyHTTP Server

Which status code means "Not Found"?

Multiple choicemediumHTTP Server

What does new URL(req.url, 'http://localhost').searchParams.get('page') return for /list?page=3?

Predict the outputmediumHTTP Server

A POST successfully creates a new item. Which status code should the server send?

Multiple choicehardHTTP Server

Why does reading a request body need for await (const chunk of req)?

10Express Basics

Read the lesson
Fill in the blankseasyExpress Basics

Complete the route so it handles GET requests to /about.

app.('/about', (req, res) => res.send('About us'));
Multiple choiceeasyExpress Basics

Where does Express put the value of :id in the route /orders/:id?

Predict the outputmediumExpress Basics

A client requests /search?q=lamp&page=2. What is typeof req.query.page?

Multiple choicemediumExpress Basics

What does app.use(express.json()) do?

Multiple choicehardExpress Basics

Why should /users/me be defined before /users/:id?

11Express Routing

Read the lesson
Fill in the blankseasyExpress Routing

Complete the line to mount the router on /orders.

app.('/orders', ordersRouter);
Multiple choiceeasyExpress Routing

What does express.Router() create?

Predict the outputmediumExpress Routing

A router defines router.get('/:id', ...) and is mounted with app.use('/api/users', router). Which URL matches?

Multiple choicemediumExpress Routing

What does router.route('/:id') let you do?

Multiple choicehardExpress Routing

Why would you use router.param('id', ...)?

12Middleware

Read the lesson
Fill in the blankseasyMiddleware

Complete the middleware so the request continues to the route.

app.use((req, res, next) => {
  req.startedAt = Date.now();
  ();
});
Multiple choiceeasyMiddleware

What are the three parameters of normal Express middleware?

Multiple choicemediumMiddleware

What happens if middleware neither calls next() nor sends a response?

Predict the outputmediumMiddleware

In which order are the messages printed for GET /?

app.use((req, res, next) => { console.log('A'); next(); });
app.get('/', (req, res) => { console.log('C'); res.end(); });
app.use((req, res, next) => { console.log('B'); next(); });
Multiple choicehardMiddleware

Why write requireRole('admin') as a function that returns middleware?

Fill in the blankseasyREST API

Complete the line so a new product returns the Created status.

res.status().json(product);
Multiple choiceeasyREST API

Which method and URL should fetch product 42?

Multiple choicemediumREST API

What's the difference between PUT and PATCH?

Predict the outputmediumREST API

With 23 items and limit=5, how many pages are there?

Multiple choicehardREST API

Why cap the limit query parameter at a maximum?

14Validation

Read the lesson
Fill in the blankseasyValidation

Complete the schema so price must be a number.

const Item = z.object({ price: z.().positive() });
Multiple choiceeasyValidation

Which status code should an API return for invalid input?

Multiple choicemediumValidation

What's the difference between parse and safeParse in Zod?

Predict the outputmediumValidation

What does this print?

const S = z.object({ n: z.coerce.number() });
console.log(S.parse({ n: '42' }).n + 1);
Multiple choicehardValidation

Why validate on the server when the browser form already validates?

15Static Files & Templates

Read the lesson
Fill in the blankseasyStatic Files & Templates

Complete the line to serve the public folder.

app.use(express.(path.join(import.meta.dirname, 'public')));
Multiple choiceeasyStatic Files & Templates

Which EJS tag outputs a value safely escaped?

Multiple choicemediumStatic Files & Templates

What does res.download do?

Predict the outputmediumStatic Files & Templates

app.use('/static', express.static('public')) is set up. Which URL returns public/img/logo.png?

Multiple choicehardStatic Files & Templates

Why redirect with 303 after a successful form POST?

16Error Handling

Read the lesson
Fill in the blankseasyError Handling

Complete the error-handling middleware's parameter list.

app.use((err, req, res, ) => {
  res.status(500).json({ error: 'Something went wrong' });
});
Multiple choiceeasyError Handling

Where should the error-handling middleware be added?

Multiple choicemediumError Handling

What's an operational error?

Predict the outputmediumError Handling

What does this print?

try {
  throw new Error('outer', { cause: new Error('inner') });
} catch (e) {
  console.log(e.cause.message);
}
Multiple choicehardError Handling

What should an uncaughtException handler normally do?

Fill in the blankseasyStreams

Complete the line to connect the streams safely.

await (createReadStream('a.txt'), createGzip(), createWriteStream('a.txt.gz'));
Multiple choiceeasyStreams

What's the main benefit of streams for large files?

Multiple choicemediumStreams

Which kind of stream changes data as it passes through?

Multiple choicemediumStreams

Why use readline instead of splitting chunks on newlines yourself?

Multiple choicehardStreams

What is backpressure?

18Databases

Read the lesson
Fill in the blankseasyDatabases

Complete the query so the value is passed safely.

db.prepare('SELECT * FROM users WHERE id = ').get(userId);
Multiple choiceeasyDatabases

Which method returns every matching row from a prepared statement?

Multiple choicemediumDatabases

What is SQL injection?

Predict the outputmediumDatabases

A transaction inserts an order and then the stock update throws. After ROLLBACK, how many new orders exist?

Multiple choicehardDatabases

Why use a connection pool with PostgreSQL?

19Authentication

Read the lesson
Fill in the blankseasyAuthentication

Complete the cookie option that stops page scripts from reading the cookie.

res.cookie('sid', id, { : true, secure: true, sameSite: 'lax' });
Multiple choiceeasyAuthentication

What should a database store for each user's password?

Multiple choicemediumAuthentication

What's the difference between authentication and authorisation?

Multiple choicemediumAuthentication

Can anyone read the payload of a JWT?

Multiple choicehardAuthentication

Why does each password hash use its own random salt?

Fill in the blankseasySecurity

Complete the status code for too many requests.

res.status().json({ error: 'Slow down' });
Multiple choiceeasySecurity

Which package sets a group of protective HTTP headers in Express?

Multiple choicemediumSecurity

What does a path traversal attack try to do?

Multiple choicemediumSecurity

Why use execFile with an argument array instead of exec with a string?

Multiple choicehardSecurity

Why is cors({ origin: true, credentials: true }) dangerous?

Fill in the blankseasyTesting

Complete the check that compares two arrays by content.

assert.([1, 2], [1, 2]);
Multiple choiceeasyTesting

Which command runs Node's built-in test runner?

Multiple choicemediumTesting

How do you check that an async function rejects?

Predict the outputmediumTesting

What does fn.mock.callCount() return here?

const fn = mock.fn();
fn(1);
fn(2);
fn(3);
Multiple choicehardTesting

Why pass dependencies such as a payment service into a function instead of importing them directly?

22WebSockets

Read the lesson
Fill in the blankseasyWebSockets

Complete the line to send a JSON message over the socket.

socket.(JSON.stringify({ type: 'hello' }));
Multiple choiceeasyWebSockets

What's the main advantage of WebSockets over repeated HTTP requests?

Multiple choicemediumWebSockets

Which event does a ws socket emit when a message arrives?

Multiple choicemediumWebSockets

When are Server-Sent Events a better choice than WebSockets?

Multiple choicehardWebSockets

Why add a heartbeat with ping and pong?

23Processes & Workers

Read the lesson
Fill in the blankseasyProcesses & Workers

Complete the line that sends a result from a worker back to the main thread.

parentPort.(result);
Multiple choiceeasyProcesses & Workers

What happens to other requests while a Node server runs a long CPU-heavy loop on the main thread?

Multiple choicemediumProcesses & Workers

Which function streams a child process's output as it's produced?

Multiple choicemediumProcesses & Workers

How does data get into a worker thread when it starts?

Multiple choicehardProcesses & Workers

Would worker threads speed up an API whose time is spent waiting on database queries?

24Debugging & Performance

Read the lesson
Fill in the blankseasyDebugging & Performance

Complete the command that starts Node with the debugger listening.

node -- server.js
Multiple choiceeasyDebugging & Performance

What does the debugger; statement do?

Multiple choicemediumDebugging & Performance

What does a high event-loop delay tell you?

Multiple choicemediumDebugging & Performance

What's the N+1 query problem?

Multiple choicehardDebugging & Performance

Why does a cache need a size limit or expiry in a long-running server?

25Deployment

Read the lesson
Fill in the blankseasyDeployment

Complete the line so the port comes from the environment.

app.listen(Number(process.env. ?? 3000));
Multiple choiceeasyDeployment

Which command installs exactly the versions in the lock file without dev dependencies?

Multiple choicemediumDeployment

What should a readiness endpoint return while the app is shutting down?

Multiple choicemediumDeployment

Why should a container run as a non-root user?

Multiple choicehardDeployment

Why copy package.json and the lock file before the rest of the source in a Dockerfile?

26Buffers and UTF-8

Read the lesson
Multiple choiceeasyBuffers and UTF-8

The worked packet contains UTF-8 é. What header length must be written?

27URL and URLSearchParams

Read the lesson
Multiple choiceeasyURL and URLSearchParams

In the fixture, how many values does getAll("tag") return after set("q", ...)?

28Integrity and Webhook HMAC

Read the lesson
Multiple choiceeasyIntegrity and Webhook HMAC

What happens when the main fixture only changes JSON whitespace while keeping the original signature?

29HTTPS and TLS Verification

Read the lesson
Multiple choiceeasyHTTPS and TLS Verification

Why does the complete fixture trust its self-signed demonstration certificate?

30DNS Resolution

Read the lesson
Multiple choiceeasyDNS Resolution

What TTL does the main Resolver receive for fixture.test?

31TCP Message Framing

Read the lesson
Multiple choiceeasyTCP Message Framing

When the practice feeds two frames as one combined chunk, how many messages are emitted?

32Compression Formats and HTTP

Read the lesson
Multiple choiceeasyCompression Formats and HTTP

What happens to the valid 100-byte gzip fixture under maxOutputLength: 10?

33Timers and Microtasks

Read the lesson
Multiple choiceeasyTimers and Microtasks

How many items have been processed when the worked checkpoint prints?

34Fetch Bodies and Cancellation

Read the lesson

What happens when boundedText receives abcdef with a five-byte limit?

35Interactive Readline CLIs

Read the lesson
Multiple choiceeasyInteractive Readline CLIs

What decision does the worked confirmation produce for NO?

36Package Exports and Imports

Read the lesson
Multiple choiceeasyPackage Exports and Imports

Which implementation does createRequire select in the worked dual package?

37AsyncLocalStorage Request Context

Read the lesson

What does the bound callback print when invoked inside caller in the worked example?

38Web Streams Interoperability

Read the lesson
Multiple choiceeasyWeb Streams Interoperability

What results do the two worked tee consumers produce?

39HTTP/2 Sessions and Streams

Read the lesson
Multiple choiceeasyHTTP/2 Sessions and Streams

How many client sessions does the worked /a and /b example create?

40Native TypeScript Type Stripping

Read the lesson

Which worked inputs pass isQuantity?

41Node Permission Model

Read the lesson
Multiple choiceeasyNode Permission Model

What does the worked directory grant report for a.txt and b.txt?

42Bounded File Uploads

Read the lesson
Multiple choiceeasyBounded File Uploads

How many files remain after the worked seven-byte upload exceeds its six-byte limit?

43Diagnostics Channel Instrumentation

Read the lesson

Why is the worked totalMs 15 rather than 115?

Next steps