Node.js Quiz: Test Your Node.js Knowledge
Pick how many questions you want, choose a difficulty and go. You'll see why each answer is right or wrong, then you can retry to beat your score.
What does REPL stand for?
- Run Every Program Line
- Remote Execution Process Layer
- Repeat Each Previous Line
- Read-Eval-Print Loop
Which Node versions are recommended for production?
- Odd-numbered Current releases
- LTS (Long Term Support) releases
- Nightly builds
- Any version
What does process.argv contain?
- Environment variables
- The current directory
- The command-line arguments
- The Node version
Which runs first?
- A Promise .then callback
- A setTimeout callback with 0 ms
- They run at the same time
- It's random
What happens if your code runs a long synchronous loop?
- The event loop is blocked, so no other requests or callbacks can run
- Node runs it on another thread
- Node stops the loop automatically
- Nothing special
What does the node: prefix in
import fs from 'node:fs'show?- The module comes from npm
- The module is a CommonJS module
- The module is optional
- The module is built into Node.js
How does CommonJS export values?
- export default
- module.exports = { ... }
- exports default
- return { ... }
What does dynamic import() return?
- The module directly
- A string
- A promise that resolves to the module
- Nothing
How many default exports can a module have?
- None
- One
- Two
- Any number
Which file extension always means an ES module, whatever package.json says?
- .js
- .cjs
- .json
- .mjs
What does npx do?
- Deletes packages
- Runs a package's command without a permanent install
- Publishes a package
- Updates npm
In version 3.8.2, what does the 8 represent?
- Major
- Patch
- Minor
- Build
Should package-lock.json be committed to Git?
- No
- Only for libraries
- Only on Windows
- Yes
Which command checks installed packages for known security problems?
- npm check
- npm secure
- npm verify
- npm audit
Which scripts can be run without the word run?
- Any script
- start and test
- dev and build
- None
Which function adds text to the end of a file?
- appendFile
- writeFile
- addFile
- readFile
What does mkdir with { recursive: true } do?
- Deletes folders recursively
- Lists folders
- Creates any missing parent folders and doesn't fail if the folder exists
- Copies folders
What does readFile return when no encoding is given?
- A string
- An array of lines
- null
- A Buffer of bytes
Relative paths in fs calls are resolved against which folder?
- The current working directory where node was started
- The script's folder
- The home folder
- node_modules
Which is the safer way to read a file that might not exist?
- Check with existsSync, then read
- Use writeFile first
- Use stat in a loop
- Try to read it and handle the ENOENT error
Which module helps build file paths?
- fs
- path
- os
- url
What does os.homedir() return?
- The project folder
- The temporary folder
- The current user's home folder
- The Node install folder
What does path.dirname('/a/b/c.txt') return?
- c.txt
- /a
- /a/b
- .txt
Which value is the separator for the current operating system?
- os.EOL
- path.delimiter
- os.sep
- path.sep
What does new URL('https://a.dev/x?q=1').searchParams.get('q') return?
- 1 (a number)
- '1' (a string)
- null
- q=1
Which method adds a listener that runs every time an event is emitted?
- once
- emit
- on
- off
How do you remove a listener?
- emit('remove')
- delete emitter[name]
- off(name, sameFunction)
- on(name, null)
What does await once(emitter, 'ready') give you?
- The emitter
- true
- The listener count
- An array of the arguments passed to the event
What does a MaxListenersExceededWarning usually point to?
- Listeners being added repeatedly, which leaks memory
- A slow listener
- An error event
- Too many emitters
Which is a good fit for events rather than a single promise?
- Reading one file
- Progress updates that happen many times during an upload
- A single database query
- Parsing one JSON string
Where should API keys for a server be stored?
- In the source code
- In package.json
- In environment variables
- In a comment
How do you load a .env file with Node's built-in support?
- node --dotenv
- import '.env'
- npm env
- node --env-file=.env app.js
What does process.cwd() return?
- The current working directory
- The script's folder
- The home folder
- The Node version
What should be committed instead of a real .env file?
- Nothing
- A .env.example with variable names and dummy values
- The production .env
- A zip of .env
Why is
if (process.env.ENABLED)a bug when ENABLED is "false"?- "false" is a non-empty string, which is truthy
- It isn't
- process.env is undefined
- It throws an error
In an error-first callback, what is the first argument?
- The result
- The file name
- An error, or null if there was none
- A promise
How do you handle an error from an awaited promise?
- With .then only
- With try/catch around the await
- Errors can't happen
- With process.exit
Which method resolves with the first promise to succeed?
- Promise.any
- Promise.all
- Promise.race
- Promise.allSettled
What does util.promisify do?
- Makes code faster
- Converts an error-first callback function into one that returns a promise
- Creates a timer
- Catches every error
What happens in modern Node when a rejected promise is never handled?
- Nothing
- It's retried
- An error is reported and the process exits
- It's logged and ignored forever
Which built-in module creates a web server?
- node:net only
- node:web
- node:http
- node:server
Which HTTP method is usually used to create a resource?
- GET
- DELETE
- HEAD
- POST
Which header tells the client that the body is JSON?
- Accept: application/json
- Body-Type: json
- Content-Type: application/json
- Format: json
Does fetch throw an error when the server responds with 500?
- No, check response.ok or response.status
- Yes
- Only for POST requests
- Only in Node
What does status 405 mean?
- The resource moved
- The method isn't allowed for this URL
- The server is overloaded
- Authentication is required
Which method sends JSON with the right Content-Type?
- res.send
- res.write
- res.end
- res.json
How do you send a 404 with a JSON message?
- res.json(404, {...})
- res.status(404).json({ error: 'Not found' })
- res.send404()
- res.error(404)
What error appears if a handler sends two responses?
- Cannot set headers after they are sent
- 404
- Unexpected token
- ECONNRESET
Which response suits a successful DELETE with nothing to return?
- res.json(null)
- res.redirect('/')
- res.status(500)
- res.sendStatus(204)
What does Express 5 do differently with errors thrown in async route handlers?
- Ignores them
- Restarts the server
- Passes them to the error-handling middleware automatically
- Returns 200
Where do route parameters appear?
- req.query
- req.body
- req.route
- req.params
What option lets a nested router read its parent's parameters?
- strict: true
- mergeParams: true
- caseSensitive: true
- nested: true
How is an optional path segment written in Express 5?
- /files{/:name}
- /files/:name?
- /files/[name]
- /files/*name?
What's a good way to organise routes in a growing project?
- One file for every route
- Everything in app.js
- One router per feature, mounted under a prefix
- One router for GET and one for POST
In Express 5, what does a named wildcard like /docs/*path put in req.params.path?
- A string
- A number
- An array of the matched segments
- Nothing
Which line applies middleware to every request?
- app.get(fn)
- app.use(fn)
- app.all(fn)
- app.listen(fn)
What does the cors package do?
- Lets browsers on other domains call your API
- Compresses responses
- Logs requests
- Parses cookies
Which status should authentication middleware send when no valid login is present?
- 403
- 404
- 500
- 401
How do you apply middleware to just one route?
- app.use only
- Put it in package.json
- It's not possible
- Pass it before the handler: app.get('/x', check, handler)
How can middleware run code after the response has been sent?
- By calling next twice
- By using setTimeout
- By listening for the response's finish event
- It can't
Which status code fits a successful DELETE with no body?
- 204
- 200
- 201
- 404
What should a POST response include besides the new item?
- A redirect
- A Location header with the new item's URL
- The full list
- Nothing
Why put data logic in a service module instead of in routes?
- Express requires it
- It keeps routes thin and lets the logic be tested and reused without HTTP
- It makes responses faster
- Services are needed for JSON
What does sort=-price usually mean?
- Sort by price, highest first
- Remove the price field
- Sort by price, lowest first
- Filter out negative prices
Why version an API with a prefix like /api/v1?
- It's faster
- Browsers require it
- To hide the API
- Breaking changes can go into v2 while existing clients keep using v1
What type are route parameters and query values in Express?
- Whatever type they look like
- Numbers
- JSON
- Strings
What does a Zod object schema do with unknown keys by default?
- Removes them from the parsed result
- Rejects the data
- Keeps them
- Converts them to strings
Which Zod method gives a value when a field is missing?
- .optional()
- .nullable()
- .fill(value)
- .default(value)
Where should validation happen in an Express app?
- Deep in the database code
- At the edge, in the route or a validation middleware, before the data is used
- Only in the browser
- After saving
Why is mass assignment, saving req.body directly, dangerous?
- It's slow
- JSON can't be saved
- Clients can set fields they shouldn't, such as a role or a balance
- It loses data
Which middleware parses HTML form submissions?
- express.json()
- express.static()
- express.urlencoded()
- express.form()
Which files are safe to cache for a year?
- index.html
- API responses
- Every file
- Fingerprinted assets like app.3f9a1c.js whose names change with their content
What attack does escaping user content prevent?
- Cross-site scripting (XSS)
- SQL injection
- Denial of service
- Brute force
How do you render the template views/home.ejs with data?
- res.send('home', data)
- res.render('home', data)
- res.template('home.ejs')
- res.sendFile('home.ejs')
Can express.static serve files outside its folder for a URL like /../server.js?
- Yes
- Only on Windows
- No, it rejects paths that leave the folder
- Only for .js files
Which status code should an unexpected server bug produce?
- 400
- 404
- 500
- 200
How does Express 5 handle an error thrown in an async route?
- It crashes the server
- It passes the error to the error-handling middleware
- It returns 200
- It ignores it
Why give custom errors a status property?
- For speed
- JavaScript requires it
- To hide the message
- So the central error handler can choose the right HTTP status
Why throw Error objects instead of strings?
- Error objects include a stack trace and can be checked with instanceof
- Strings can't be caught
- Strings are slower
- There's no difference
Which errors are worth retrying automatically?
- Validation errors
- 404 Not Found
- Temporary failures such as 503 or a reset connection
- Syntax errors
Which function creates a readable stream from a file?
- createReadStream
- readFile
- openStream
- streamFile
What does pipeline do if one of its streams fails?
- Continues with the others
- Restarts the stream
- Nothing
- Destroys all the streams and rejects with the error
How do you finish writing to a writable stream?
- close()
- stop()
- finish()
- end()
What does Readable.from(array) do?
- Turns the array (or any iterable) into a readable stream
- Copies the array
- Reads a file
- Sorts the array
Is an HTTP response object a stream?
- No
- Only for files
- Yes, a writable stream
- Only with Express
Which built-in module gives Node SQLite support?
- node:sql
- node:db
- node:database
- node:sqlite
What does run() return after an INSERT?
- The inserted row
- true
- Nothing
- An object with changes and lastInsertRowid
What's a database migration?
- Moving to a new server
- A versioned script that changes the database structure step by step
- A backup
- A slow query
What placeholder style does the pg driver use?
- ?
- :name only
- $1, $2 and so on
- {0}
Why put queries in a repository module?
- Queries live in one place, are easy to change and can be replaced with fakes in tests
- SQL only runs there
- It's faster
- ORMs require it
Which status code means "not signed in"?
- 403
- 404
- 500
- 401
What does the Secure cookie flag do?
- Sends the cookie only over HTTPS
- Encrypts the cookie
- Hides it from JavaScript
- Makes it permanent
Why should password hashing be slow?
- To save memory
- To make guessing passwords from a leaked database very expensive
- Because crypto is slow
- It shouldn't be
What's an advantage of server-side sessions over JWTs?
- No storage needed
- They never expire
- They can be revoked instantly by deleting the session
- They work without cookies
Why compare hashes with timingSafeEqual instead of ===?
- === doesn't work on Buffers
- It's faster
- It decrypts the hash
- It takes the same time however many bytes match, so response times reveal nothing
Where should API keys and database passwords live?
- In the source code
- In environment variables or a secret manager
- In package.json
- In public/config.js
What does Content-Security-Policy help prevent?
- SQL injection
- Brute force attacks
- Slow queries
- Cross-site scripting, by limiting where scripts can load from
Which routes most need strict rate limits?
- Sign-in, sign-up and password reset
- Static images
- The home page
- Health checks
What does npm audit do?
- Reports installed packages with known vulnerabilities
- Speeds up installs
- Removes unused packages
- Encrypts node_modules
What does the principle of least privilege mean for a Node server?
- Use as few packages as possible
- Run with only the permissions it needs, for example as a non-root user with a limited database account
- Give every user admin rights
- Disable logging
Which module provides test, describe and it?
- node:assert
- node:spec
- node:check
- node:test
What does assert.equal use to compare in node:assert/strict?
- ===
- ==
- Object.is only for numbers
- JSON.stringify
How can a test move time forward without waiting?
- Enable mock timers and call mock.timers.tick(ms)
- await sleep
- Change the system clock
- It can't
How should an API test start the server?
- On port 80
- By running npm start in another terminal
- It doesn't need a server
- On port 0, so the system picks any unused port
What should good tests focus on?
- Private helper functions
- Observable behaviour: inputs, outputs and errors
- Line-by-line implementation
- Only the happy path
Which URL scheme is used for secure WebSockets?
- https://
- ws+ssl://
- wss://
- sws://
How do you send a message to every connected client with ws?
- wss.sendAll()
- socket.broadcast()
- Loop over wss.clients and send to each open socket
- It isn't possible
What Content-Type does a Server-Sent Events response use?
- text/event-stream
- application/json
- text/plain
- application/sse
Why include a type field in WebSocket messages?
- It's required by the protocol
- To compress them
- For security
- So each side knows how to handle each kind of message
How do several WebSocket servers share messages so every client receives them?
- They can't
- Through a shared message channel such as Redis pub/sub
- By using one port
- By sending larger messages
Which module provides Worker and parentPort?
- node:child_process
- node:worker_threads
- node:cluster
- node:os
Why pass command arguments as an array to execFile?
- They aren't interpreted by a shell, which prevents command injection
- It's faster
- Arrays are required by Windows
- To run in parallel
What does the cluster module do?
- Groups database rows
- Creates worker threads
- Compresses responses
- Starts several Node processes that share a server port to use more CPU cores
Why use a worker pool rather than a new worker per task?
- Pools are required
- Pools share variables
- Starting workers is slow and uses memory; a pool reuses a fixed set
- Workers can only run once
Is data passed with postMessage shared or copied between threads by default?
- Copied
- Shared
- Deleted
- Encrypted
Which method shows an array of objects as a table?
- console.dir
- console.table
- console.grid
- console.list
What is structured logging?
- Writing each log entry as data, such as one JSON object per line with fields
- Logging only errors
- Logging in a table
- Logging to separate files
Which flag records a CPU profile?
- --profile-cpu
- --inspect-cpu
- --cpu-prof
- --trace
What should you do before optimising code for speed?
- Rewrite it
- Add more servers
- Measure where the time actually goes
- Remove logging
Which tool helps find which objects are filling memory?
- console.time
- A heap snapshot in Chrome DevTools
- npm audit
- node --watch
Which signal do platforms send to stop a Node process gracefully?
- SIGKILL
- SIGHUP
- SIGTERM
- SIGSTOP
What does NODE_ENV=production change in Express?
- Nothing
- It disables routing
- It turns on debug logging
- It enables caching and less detailed error pages
Where should a production Node app write its logs?
- Standard output, collected by the platform
- A file inside the container
- The database
- Nowhere
What does a CI/CD pipeline usually do before deploying?
- Nothing
- Installs dependencies, lints, runs tests and checks for vulnerabilities
- Deletes the database
- Asks every developer for approval by email
Why split an Express app into app.js and server.js?
- Express requires two files
- It makes responses faster
- To use two ports
- Tests and tools can import the app without starting a real server
Which operation creates independent storage for an existing Buffer view?
- Buffer.from(view)
- view.subarray(0)
- view.slice(0)
Why use StringDecoder for chunked UTF-8?
- It retains incomplete character bytes between chunks
- It guarantees every network chunk contains complete JSON
- It changes the socket into a text-only transport
Why reject duplicate page parameters before Number conversion?
- Different layers might otherwise use different occurrences
- Number conversion removes all duplicate keys automatically
- URLSearchParams rejects repeated names during parsing
Which check identifies the complete trusted redirect origin?
- Compare parsed target.origin with the configured origin
- Check whether the original string starts with the trusted hostname
- Search for the trusted hostname anywhere in pathname
What does an HMAC provide for a webhook body?
- Integrity and authentication for parties sharing the secret
- Encryption that prevents observers reading the body
- A guarantee that the event has never been delivered before
Why check hexadecimal shape before Buffer.from?
- Decoding alone is not a strict signature-format validator
- Hexadecimal decoding always rejects every malformed character
- The check converts SHA-256 into a password hashing algorithm
Which result proves only a hostname match?
- A successful offline checkServerIdentity call
- A complete verified TLS handshake with a trusted certificate
- An HTTPS request that verified its chain and hostname
What is the appropriate response to an unknown internal certificate authority?
- Configure the intended authority as trusted for the client
- Set rejectUnauthorized to false for every request
- Ignore the error if the response status would be 200
Which operation can use operating-system sources such as a hosts file?
- lookup
- resolveMx
- resolveTxt
What does querying resolve4 request?
- A records representing IPv4 addresses
- Every available DNS record in one combined response
- The operating system process ID for a hostname
What guarantee does TCP provide to this parser?
- Ordered bytes within the connection
- One data event for each sender write
- Automatic JSON validation for every payload
Which length belongs in the fixture header for café?
- Its UTF-8 byte length
- Its JavaScript string length regardless of encoding
- The number of data events received
Which HTTP length describes a compressed response body?
- The number of transmitted compressed bytes
- The original JavaScript string length
- The number of JSON object properties
Why emit Vary: Accept-Encoding when encodings differ?
- Caches need to distinguish representations selected by that request header
- It forces every client to accept Brotli
- It disables content type validation
What does a timeout delay promise?
- An eligibility threshold, not an exact execution time
- An interruption of any currently running JavaScript
- A guaranteed callback time unaffected by CPU work
How can an async setInterval callback overlap its own work?
- A later tick can begin while an earlier awaited operation is unfinished
- await automatically stops future interval ticks
- Intervals are limited to one invocation for the process lifetime
Why must an unsuccessful response body be consumed or canceled before retrying?
- It owns stream and connection resources even with an error status
- fetch always consumes error bodies automatically
- A canceled body makes POST automatically idempotent
What policy makes retries appropriate for a state-changing request?
- A documented remote idempotency mechanism and bounded retry rules
- Any AbortError proves the remote action never started
- Changing POST to GET inside the client automatically fixes the endpoint
Why await each question before starting the next?
- It keeps answer ownership and conversation order explicit
- It converts every answer automatically into a number
- It hides typed characters from the terminal
Where should readline cleanup normally happen?
- In finally under the component that owns the interface
- Only after a valid numeric answer
- Inside every data callback by destroying process.stdin
What is the purpose of #settings in the main fixture?
- A private package imports mapping
- A URL fragment automatically downloaded by Node
- A public subpath available from every external package
Why test package-name imports rather than only relative source imports?
- The resolver contract can fail while relative files still work
- Relative imports always publish the package automatically
- Package-name tests remove the need to check module formats
Why is a global currentRequestId unsafe during overlapping awaits?
- Another request can overwrite it before the first resumes
- await automatically copies every global variable
- Node forbids all global variables inside servers
Why keep context stores small?
- Long-lived async work can retain their data beyond the request
- AsyncLocalStorage rejects stores with more than one property
- Small stores automatically authenticate request IDs
Which adapter connects a Web readable to a Node pipeline?
- Readable.fromWeb
- Readable.toWeb
- WritableStream.getReader
What does getReader establish?
- Exclusive reading ownership through a stream lock
- Automatic unlimited copying for every later consumer
- A conversion from objects to UTF-8 bytes
Which field supplies the response status in the low-level server?
- The :status pseudo-header
- A Connection: status=200 header
- The session URL fragment
What remains necessary for browser-facing secure HTTP/2?
- Valid TLS configuration and appropriate protocol negotiation
- Only changing the content type to application/http2
- Disabling hostname verification so ALPN can succeed
What does a TypeScript assertion do to untrusted JSON at runtime?
- It does not validate or convert the value
- It checks every property against the interface
- It automatically rejects unknown fields
Which feature is outside default erasable stripping?
- An enum requiring generated JavaScript
- A type alias
- A parameter type annotation
What does ERR_ACCESS_DENIED represent in the main child?
- The selected resource operation was not granted by the enabled model
- The file must be missing from the operating system
- The trusted code has been proven malicious
Why avoid responding to every denial with --allow-fs-read=*?
- It replaces the narrow intended authority with broad filesystem read access
- The wildcard limits access only to one extension
- It gives write access but leaves read access unchanged
Why count actual request bytes as well as inspect Content-Length?
- The declared length is not the entire enforcement policy and may be absent
- Every request body always contains exactly one byte per character
- Content-Length automatically validates every uploaded format
Why not place every accepted upload directly in a public static directory?
- Acceptance and public download authorization are separate decisions
- randomUUID automatically grants safe public access
- A static directory prevents file processing errors
What happens to the main sale calculation after unsubscribe?
- It still returns the required total without observation
- It must fail because no monitor authorizes it
- It waits until another subscriber appears
Why avoid mutating a published message in a subscriber?
- Other subscribers may observe the same payload object
- publish clones every message deeply before every callback
- Mutation automatically makes an event durable
About the Node.js quiz
This Node.js quiz covers every lesson in the course, from running scripts and modules to Express, databases, security and deployment. Many questions show a few lines of Node code and ask what they print or which status code a server returns, because predicting behaviour is the best way to check that you understand it. Others check vocabulary you'll meet in documentation and job interviews, such as "event loop", "middleware", "prepared statement" and "graceful shutdown".
If you're still in the beginner stage, choose Easy and a topic you've just finished, such as modules or the file system. After the intermediate lessons, try Mixed with 10 questions to practise Express, REST and validation together. Save Exam mode for the end of the course: it hides the answers until you finish, so it's an honest check of what you remember.
When you miss a question, read the explanation and revisit the lesson linked in your results. Node mistakes often come from small details: a missing await, forgetting that query values are strings, or middleware that never calls next(). Spotting them in a quiz makes them easy to avoid in real code.
The question bank holds 161 questions drawn from 43 Node.js lessons: 43 easy, 93 medium and 25 hard. Every time you start, the quiz picks a fresh random selection that matches your settings, so retaking it is a good way to practise. After each answer, or at the end in exam mode, you'll see why the right answer is right, and every question you miss links back to the lesson that teaches it.
What the Node.js quiz covers
Beginner
Intermediate
Advanced
Runtime and network references
Tools and application boundaries
- 35Node.js Interactive Readline CLIs
- 36Node.js Package Exports and Imports
- 37Node.js AsyncLocalStorage Request Context
- 38Node.js Web Streams Interoperability
- 39Node.js HTTP/2 Sessions and Streams
- 40Node.js Native TypeScript Type Stripping
- 41Node.js Permission Model
- 42Node.js Bounded File Uploads
- 43Node.js Diagnostics Channel Instrumentation