Level 4 · Full-Stack Application Development · Course 4.3 Backend with Node.js

Module 45: Files and Logging

Goal: work with files on the server, accept uploads safely, and keep structured logs and error reports, so you can find out what happened when something goes wrong.

You'll need: your enquiries-api with sign-in from Module 44.

Lessons

  1. 1File operations15–25 minutes✓
  2. 2File uploads15–25 minutes✓
  3. 3Validating uploads15–25 minutes✓
  4. 4Structured logging15–25 minutes✓
  5. 5Error reports and monitoring15–25 minutes✓

🛠️Module practice: attachments and observability

  1. Safe file writes and a safePath helper.
  2. Enquiry attachments: size and type limits checked by content, random names, signed-in downloads.
  3. Structured JSON logs with request ids, levels and redaction.
  4. Error reporting for unexpected errors; a health check; graceful shutdown.
  5. Nothing secret in logs. Commit.

✅Module check

Explain in a few sentences, in your own words:

How do you handle uploaded files safely, and how do you find out what went wrong in a running server?

Show a good answer

A good answer mentions: limit upload size and count, check type by content against a short allow-list, store files under generated names (ideally in object storage, with details in the database), never build paths from user input (path traversal), and serve files with safe headers after checking permission. To investigate problems: structured JSON logs with levels and request ids, without passwords, tokens or unnecessary personal data; error reporting with alerts for unexpected errors; health checks, uptime monitoring and graceful shutdown.

📝Module quiz

10 questions · 10 marks each · 100 marks in all · pass mark 70% · retry as often as you like ·

1. What's path traversal?

Why each option is right or wrong

  • “Moving an uploaded file between folders on the server after saving it” (Incorrect): Moving files is normal; traversal is an attack using ../.
  • “A slow file system that takes a long time to find each path” (Incorrect): It's a security attack, not a speed problem.
  • “Following links between pages of a website” (Incorrect): That's navigation; path traversal is about server file paths.
  • “Using ../ in a file name to reach files outside the intended folder” is correct.

    If a server builds a path like uploads/ + a name from the user, a name such as ../../.env climbs out of the uploads folder and could read or overwrite secret files. The fix is not to trust names from users: generate your own, or resolve the path and check it stays inside the folder.

    • Check: path.resolve(base, name).startsWith(base + path.sep).
    • Best: don't use user-supplied names for paths at all.

📖 Revise: Lesson 1: File operations

Question ID module-45-q1 · Report a mistake in this question
2. Why write to a temporary file and then rename it?

Why each option is right or wrong

  • “Renaming makes the file noticeably smaller on the disk” (Incorrect): Renaming doesn't change size; it makes the swap safe.
  • “Temporary files are encrypted automatically by the system” (Incorrect): Temporary files aren't encrypted; the point is a safe swap.
  • “Node can't write directly to files with a .json name” (Incorrect): Node can write any file; this pattern protects against crashes.
  • “A crash during writing can't leave a half-written file” is correct.

    Writing takes time. If the server crashes halfway, the file is left broken. Writing to data.json.tmp first and renaming it to data.json only once complete means the real file is either the old version or the new one, not half of each.

    • Why it works: a rename on the same disk happens in one step.
    • Keep a backup: for extra safety with important data.

📖 Revise: Lesson 1: File operations

Question ID module-45-q2 · Report a mistake in this question
3. Why save uploads under a random id instead of the original name?

Why each option is right or wrong

  • “Random names make the uploaded files load faster for visitors” (Incorrect): Speed is the same; the benefit is safety and no clashes.
  • “Servers can't store file names that contain spaces” (Incorrect): Servers can; the real risks are clashes, ../ and leaks.
  • “Search engines can't find files with random names, which is the goal” (Incorrect): Search isn't the reason; safety and avoiding clashes are.
  • “Original names can clash, contain ../ or reveal information” is correct.

    Two people uploading photo.jpg would overwrite each other. A name might include ../ to escape the folder, or personal details. A random id avoids all three; store the original name separately if you need to show it.

    • Example: uploads/3f9a2c...jpg, with the original name in the database.
    • Extension: choose it from the checked file type, not the name.

📖 Revise: Lesson 2: File uploads

Question ID module-45-q3 · Report a mistake in this question
4. A file is called photo.jpg and the browser says image/jpeg. Can you trust it's a JPEG?

Why each option is right or wrong

  • “Yes, the browser checks the type before uploading the file” (Incorrect): The browser guesses from the name; it doesn't verify the content.
  • “Yes, the .jpg extension can only be given to real images” (Incorrect): Any file can be renamed with any extension.
  • “Only if the file is smaller than one megabyte in size” (Incorrect): Size doesn't prove what a file contains.
  • “No, both can be faked; check the actual content” is correct.

    The file name and the type the browser reports are both chosen by the sender. Anyone can name a script photo.jpg. Check the file's first bytes (its "magic number"), or process it with an image library that rejects anything that isn't a real image.

    • Safer still: re-encode images, which strips hidden content.
    • Also limit: file size and image dimensions.

📖 Revise: Lesson 3: Validating uploads

Question ID module-45-q4 · Report a mistake in this question
5. Why can accepting SVG or HTML uploads be dangerous?

Why each option is right or wrong

  • “They are much larger than other image formats” (Incorrect): SVGs are often small; the danger is scripts inside them.
  • “They can't be shown in most browsers” (Incorrect): Browsers show them easily, which is why scripts inside can run.
  • “They use up the server's processor while being stored” (Incorrect): Storing them is cheap; serving them can run scripts.
  • “They can contain scripts that run in visitors' browsers” is correct.

    SVG is an image format written in XML that can include <script>. If you serve an uploaded SVG or HTML file from your own site, its script runs with your site's permissions and could steal sessions.

    • Options: don't accept them, convert them, or serve from a separate domain.
    • Headers: Content-Disposition: attachment makes browsers download rather than open them.

📖 Revise: Lesson 3: Validating uploads

Question ID module-45-q5 · Report a mistake in this question
6. Why write logs as JSON rather than plain sentences?

Why each option is right or wrong

  • “JSON logs take up less space on the disk than plain text” (Incorrect): They can be slightly larger; the gain is searchability.
  • “Plain sentences can't be written to a log file” (Incorrect): They can; they're just harder to search and filter.
  • “JSON logs hide sensitive data from the people who read them” (Incorrect): JSON doesn't hide anything; you must leave secrets out yourself.
  • “Consistent fields can be searched and filtered by tools” is correct.

    A line like {"level":"error","route":"/enquiries","userId":"u7","ms":420} can be filtered by level, route or user in a log tool. Free-form sentences need fragile text searches.

    • Common fields: time, level, message, request id.
    • Libraries: pino and winston write structured logs.

📖 Revise: Lesson 4: Structured logging

Question ID module-45-q6 · Report a mistake in this question
7. Should you log the password when a sign-in fails?

Why each option is right or wrong

  • “Yes, so you can see what the person typed and help them sign in” (Incorrect): Passwords in logs are a serious leak risk; help people with a reset instead.
  • “Yes, as long as the log file itself is kept private” (Incorrect): Logs travel to many tools and people; private files still leak.
  • “Only for admin accounts, which need closer monitoring” (Incorrect): Admin passwords are the most valuable of all to keep out of logs.
  • “No; log the email or user id, time and reason” is correct.

    Logs are read by many people and tools and often kept for a long time. A failed sign-in's password might be a typo of the real one, or a real password for another site. Record who, when and why, but not the password itself.

    • Also keep out of logs: tokens, card numbers, full personal details.
    • Useful fields: user id, IP address, reason such as "wrong password".

📖 Revise: Lesson 4: Structured logging

Question ID module-45-q7 · Report a mistake in this question
8. What should a server do when it receives SIGTERM during a deploy?

Why each option is right or wrong

  • “Exit immediately, so the new version starts as fast as possible” (Incorrect): Requests in progress would be cut off mid-way.
  • “Ignore it and keep running until the deploy is over” (Incorrect): The host will force-kill it, cutting requests off anyway.
  • “Restart itself straight away on the same port” (Incorrect): The host starts the new version; the old one should shut down cleanly.
  • “Stop new requests, finish current ones, close connections and exit” is correct.

    During a deploy, the host sends SIGTERM to say "please stop". A graceful shutdown stops accepting new requests, lets in-flight ones finish, closes the database connections and then exits, so no one's request is cut off.

    • In Node: process.on("SIGTERM", ...) then server.close().
    • Time limit: hosts force a stop if it takes too long.

📖 Revise: Lesson 5: Error reports and monitoring

Question ID module-45-q8 · Report a mistake in this question
9. Why keep uploads in object storage rather than on the server's disk?

Why each option is right or wrong

  • “Server disks can't store image files at all” (Incorrect): They can; the problems are losing files and sharing them across servers.
  • “Object storage scans every file for viruses automatically” (Incorrect): Some services offer scanning, but that isn't the main reason.
  • “It's the only way to make files public on the web” (Incorrect): Servers can serve files too; object storage is more durable and scalable.
  • “It's durable and shared between servers” is correct.

    Server disks can be wiped on redeploy, and with two servers each would have different files. Object storage like Amazon S3 or Cloudflare R2 keeps files safely, available to every server, and scales without managing disks.

    • Store in the database: just the file's key and details.
    • Serving: signed URLs can give temporary access to private files.

📖 Revise: Lesson 2: File uploads

Question ID module-45-q9 · Report a mistake in this question
10. Why use an error-reporting service if you already log errors?

Why each option is right or wrong

  • “Logs are deleted every time the server restarts” (Incorrect): Logs can be kept; error services make them easier to act on.
  • “Error services fix the bugs for you automatically” (Incorrect): They report and organise; you still fix the bugs.
  • “Logging errors to a file is against data protection law” (Incorrect): Logging is lawful when done carefully; error services add grouping and alerts.
  • “It groups errors, shows impact and alerts you” is correct.

    Logs contain every line; finding errors in them takes effort. Services like Sentry group repeated errors together, show how many users are affected and which release introduced them, and alert you when something new appears.

    • Includes: stack traces, browser and device details, breadcrumbs.
    • Keep personal data out: configure what's sent.

📖 Revise: Lesson 5: Error reports and monitoring

Question ID module-45-q10 · Report a mistake in this question

ProLearners Assist