ETE Practice Questions

INT222

Q1. Coding Problem

(Unit I - Handling Data I/O in Node.js):
Create a robust Node.js script for a log management system. Your script must perform the following tasks sequentially:

A. Create a readable stream to read a large text file named 'system.log'.
B. Create a writable stream to a new file named 'archive.log.gz'.
C. Use the Zlib module to compress the data as it flows from the readable stream to the writable stream (piping).
D. Implement a 'finish' event listener to print "Log archiving completed" to the console.
E. Use the 'fs' module to delete the original 'system.log' only after the compression is successfully finished.

Q2. Coding Problem

(Unit I - Getting Started with Node.js):
Demonstrate the use of EventEmitter and async/await to simulate an order processing system. Create a Node.js script that:

A. Imports the events module and initializes an EventEmitter instance.
B. Defines an async function processOrder(orderId) that simulates a database delay (2 seconds) using setTimeout wrapped in a Promise.
C. Emits an event named 'orderReceived' before processing starts, and 'orderShipped' after processing ends.
D. Registers listeners for these events that log messages to the console with timestamps.
E. Triggers the flow by calling processOrder for three different order IDs.

Q3. Coding Problem

(Unit II - Implementing HTTP Services):
Build a pure Node.js HTTP server (without Express) to handle basic routing and JSON responses. The server should:

A. Listen on port 3000.
B. Handle a GET request to /api/users that returns a JSON object containing a list of dummy users.
C. Handle a URL containing a query parameter (e.g., /api/users?id=1) to filter the result (manual parsing required).
D. Return a 404 Status Code and a plain text message "Route not found" for any other URL.
E. Ensure correct Content-Type headers are set for both JSON and Text responses.

Q4. Coding Problem

(Unit II - Basic Websites With Node.JS):
Create an Express.js application that handles form submissions securely using body-parser and express-validator.

A. Set up an Express server running on port 5000.
B. Middleware: Use body-parser to parse JSON bodies.
C. Create a POST route /register.
D. Inside the route, use express-validator to ensure the 'email' field is a valid email and 'password' is at least 6 characters long.
E. If validation fails, return a 400 status with errors. If it passes, return a 200 status with the message "User registered".

Q5. Coding Problem

(Unit II - Basic Websites With Node.JS):
Implement a modular routing system using express.Router. Create a file structure concept where you have a main app and a separate router file for 'products'.

A. In the main app file, import Express and your custom router.
B. In the router file, define three routes: GET / (list all products), POST / (add product), and GET /:id (get product by ID).
C. Mount the router in the main app at the path /api/products.
D. Ensure the POST route accepts data using body-parser.
E. Write the code for both files (assuming they are in the same directory).

Q6. Coding Problem

(Unit III - Socket Services in Node.js):
Create a basic real-time chat server using Socket.IO. Your solution must include the server-side code to handle the following logic:

A. Initialize an HTTP server and upgrade it with Socket.IO.
B. Listen for a 'connection' event and log "A user connected".
C. Listen for a custom event 'chatMessage' sent by a client.
D. Broadcast the received message to ALL connected clients (including the sender) using io.emit.
E. Handle the 'disconnect' event to log "A user disconnected".

Q7. Coding Problem

(Unit III - Creating Middlewares):
Develop an Express application that implements session management and custom middleware.

A. Install and setup express-session.
B. Create a custom middleware function named checkAuth that checks if req.session.isLoggedIn is true. If not, respond with 403 Forbidden.
C. Create a route /login that sets req.session.isLoggedIn = true and req.session.user = 'Admin'.
D. Create a route /dashboard that uses the checkAuth middleware. If accessed, return "Welcome to Dashboard".
E. Create a route /logout that destroys the session.

Q8. Coding Problem

(Unit I - Handling Data I/O in Node.js):
Write a Node.js script that uses the fs module to perform a series of synchronous and asynchronous file operations.

A. Check if a directory named 'data' exists. If not, create it synchronously.
B. Asynchronously write a JSON object { "status": "active" } to data/config.json.
C. Upon successful write, read the file back asynchronously.
D. Parse the JSON content and log the 'status' property to the console.
E. Handle any errors that might occur during the read/write process.

Q9. Coding Problem

(Unit IV - Getting Started with MongoDB):
Using the native MongoDB driver (not Mongoose), write a Node.js script to perform CRUD operations.

A. Connect to a local MongoDB instance at mongodb://localhost:27017.
B. Select the database inventoryDB and collection items.
C. Insert a new document: { name: "Laptop", qty: 10 }.
D. Find the document where name is "Laptop" and log it.
E. Update that document to set qty to 20.
F. Close the connection when done.

Q10. Coding Problem

(Unit IV - Introduction to Mongoose):
Create a Node.js script using Mongoose to define a schema and perform database operations.

A. Connect to MongoDB using Mongoose.
B. Define a Schema for a Student with fields: name (String, required), age (Number), and major (String).
C. Create a Model from the schema.
D. Create an async function that creates a new student named "John Doe" with age 22.
E. Within the same function, find the student by name and log the result.

Q11. Coding Problem

(Unit V - Introduction to PostgreSQL):
Write a Node.js script using the pg (node-postgres) library to interact with a PostgreSQL database.

A. Configure a Client with connection details (user, host, database, password, port).
B. Connect to the database.
C. Execute a SQL query to CREATE a table named courses (columns: id SERIAL PRIMARY KEY, title TEXT, credits INT) if it doesn't exist.
D. Execute a SQL query to INSERT a record: title='Web Dev', credits=3.
E. Execute a SQL query to SELECT all rows from courses and log the output.

Q12. Coding Problem

(Unit III - Socket Services in Node.js):
Implement a Socket.IO feature specifically for 'Rooms'.

A. Server: Allow a client to emit a 'joinRoom' event with a room name. Join the socket to that room.
B. Server: Listen for 'roomMessage' (containing roomName and message). Broadcast this message ONLY to sockets in that specific room using .to(roomName).emit(...).
C. Client (Simulated code snippet): Show how a client would emit 'joinRoom' for room "TechSupport" and then send a message to it.
D. Ensure you handle the case where the user hasn't joined the room yet (basic error logging).

Q13. Coding Problem

(Unit VI - Testing and Deployment):
Create a Node.js script to perform a basic Integration Test on a REST API endpoint.

A. Assume an API exists at http://localhost:3000/api/status.
B. Use the native fetch API (available in Node 18+) or http module to send a GET request to this endpoint.
C. Check if the response status code is 200.
D. Check if the response body contains {"status":"ok"}.
E. Log "Test Passed" or "Test Failed" based on the results.

Q14. Coding Problem

(Unit II & IV - Express + Mongoose):
Create a complete Express route that performs an Update operation (CRUD) using Mongoose.

A. Assume a Mongoose model Product is already imported.
B. Create a PUT route /products/:id.
C. Use req.params.id to identify the document.
D. Use Product.findByIdAndUpdate to update the document with data from req.body.
E. Ensure the new: true option is used so the response contains the updated document, and handle errors (e.g., ID not found).

Q15. Coding Problem

(Unit I - Handling Data I/O in Node.js):
Demonstrate the use of the fs module to watch a directory for changes.

A. Create a script that uses fs.watch on a folder named 'uploads'.
B. When a file is renamed or added (eventType 'rename'), log the filename.
C. Only if the filename ends with '.txt', read the file content asynchronously.
D. Print the content to the console.
E. Ensure the script handles the case where the file might be deleted immediately (error handling on read).

Q16. Coding Problem

(Unit III - Creating Middlewares):
Implement a global error-handling middleware in Express.

A. Create a basic Express server with one route /error that deliberately throws a new Error("Something went wrong").
B. Create an application-level middleware using app.use defined after your routes.
C. The middleware function must accept 4 arguments: (err, req, res, next).
D. Inside the middleware, log the error stack.
E. Send a JSON response with status 500 and the error message.

Q17. Coding Problem

(Unit V - Introduction to PostgreSQL):
Create a transactional operation script using pg (PostgreSQL) and async/await.

A. Connect to the database.
B. Start a transaction using BEGIN.
C. Insert a user into a users table.
D. Insert a profile into a profiles table using the ID returned from the user insertion.
E. If both succeed, COMMIT. If any error occurs, ROLLBACK the transaction and log the error.

Q18. Coding Problem

(Unit II & III - HTTP & Middleware):
Create an Express application that parses Cookies.

A. Install and use cookie-parser middleware.
B. Create a route /set-cookie that sets a cookie named 'user_prefs' with value 'dark_mode' that expires in 1 hour.
C. Create a route /get-cookie that reads the 'user_prefs' cookie.
D. If the cookie exists, return "Theme: [value]". If not, return "No preferences set".

Q19. Coding Problem

(Unit VI - Testing and Deployment):
Simulate a deployment configuration check script.

A. Create a script that checks if NODE_ENV environment variable is set to 'production'.
B. If not, log a warning.
C. Check if a PORT environment variable is set; if not, default to 8080.
D. Print the final configuration object that would be used to start the server.
E. Explain in a comment (within the code) why checking NODE_ENV is important for Express apps (hint: performance/error messages).

Q20. Coding Problem

(Unit I - Stream Module):
Implement a file copy mechanism using only Streams (no fs.copyFile allowed) to handle large files efficiently.

A. Define a function copyLargeFile(source, destination).
B. Inside, create a Read Stream from source.
C. Create a Write Stream to destination.
D. Pipe the read stream to the write stream.
E. Listen for the 'data' event on the read stream to calculate and log the total bytes processed so far (progress indicator).

Q21. Coding Problem

(Unit I - Getting Started with Node.js):
Create a Node.js CLI (Command Line Interface) script that interacts with the process object.

A. Accept a user argument from the command line (e.g., node script.js --user=Alice).
B. Parse this argument to extract the name.
C. Check if the environment variable GREETING_TYPE is set. If 'formal', log "Good day, [Name]". If 'casual', log "Hey, [Name]". Default to 'Hello' if unset.
D. Measure the execution time of the script using console.time and console.timeEnd.
E. Exit the process with code 0 for success or 1 if no name argument was provided.

Q22. Coding Problem

(Unit I - Handling Data I/O in Node.js):
Write a script using the path and fs modules to organize a directory of mixed files.

A. Assume a folder downloads exists containing .txt, .json, and .jpg files.
B. Create subdirectories text, data, and images inside downloads if they don't exist.
C. Read the directory contents.
D. Iterate through the files, detect the extension using path.extname(), and move (rename) the file into the corresponding subdirectory.
E. Log each move operation.

Q23. Coding Problem

(Unit II - Implementing HTTP Services):
Implement a Node.js HTTP server that serves a static HTML file.

A. Create an index.html file programmatically (using fs) with basic content "<h1>Hello Node</h1>".
B. Create an HTTP server listening on port 8000.
C. When a request receives /, read the HTML file.
D. Serve the file with a status code of 200 and Content-Type text/html.
E. Handle the error case where the file might be missing by returning a 500 status.

Q24. Coding Problem

(Unit II - Basic Websites With Node.JS):
Demonstrate the use of app.all() and URL parameters in Express.

A. Create an Express route using app.all('/secret', ...).
B. Inside this route, log the HTTP method used (GET, POST, PUT, etc.).
C. If the method is GET, send "Access Granted". For any other method, send "Method Not Allowed" with status 405.
D. Create another route with a regex path to match any URL starting with /ab and ending with cd (e.g., /abcd, /ab123cd).
E. Respond with the captured path.

Q25. Coding Problem

(Unit III - Creating Middlewares):
Implement cookie-session (as specified in the syllabus) for a shopping cart feature.

A. Configure cookie-session with a secret key and a 24-hour expiry.
B. Create a route /add-to-cart/:item.
C. Inside the route, check if req.session.cart exists. If not, initialize it as an empty array.
D. Push the item from the URL parameter into the cart array.
E. Create a route /my-cart that displays the JSON contents of the cart.

Q26. Coding Problem

(Unit IV - Getting Started with MongoDB):
Write a Node.js script to perform database management operations (Drop and Create) using the native MongoDB driver.

A. Connect to MongoDB.
B. Check if a collection named logs exists.
C. If it exists, drop the logs collection and log "Collection Dropped".
D. Create a new collection logs.
E. Insert a default document { created: new Date(), msg: "Init" }.

Q27. Coding Problem

(Unit IV - Introduction to Mongoose):
Implement Schema Custom Validators in Mongoose.

A. Define a User schema.
B. Add a field username (String).
C. Add a field website (String). Implement a custom validator for website that returns false if the string does not start with "http".
D. Add a custom error message "Website must start with http".
E. Try to save a user with an invalid website and catch/log the specific validation error.

Q28. Coding Problem

(Unit V - Introduction to PostgreSQL):
Write a Node.js script using pg to perform a bulk insert and a parameterized query search.

A. Connect to PostgreSQL.
B. Prepare an array of arrays representing 3 students: [['Alice', 90], ['Bob', 85], ['Charlie', 92]].
C. Use a loop or a dynamic query string to INSERT all students into a grades table (name, score) in one go (or sequential awaits).
D. Perform a SELECT query using a parameter ($1) to find students with a score greater than 88.
E. Log the names of the high-scoring students.

Q29. Coding Problem

(Unit VI - Testing and Deployment):
Create a unit test script using Node.js's built-in assert module.

A. Define a function add(a, b) that returns a + b.
B. Define a function fetchData() that returns a Promise resolving to "data".
C. Write a test case using assert.strictEqual to verify add(2, 3) equals 5.
D. Write an async test case to verify fetchData() resolves to "data", using assert.match or strict equality.
E. Wrap these in a try-catch block to print "All tests passed" or the specific error.

Q30. Coding Problem

(Unit II - Basic Websites With Node.JS):
Create a robust Express setup using express-validator specifically for sanitization.

A. Create a POST route /comment.
B. Use body('comment') to select the input.
C. Chain sanitizers: .trim() to remove whitespace and .escape() to convert HTML characters (prevent XSS).
D. Inside the route handler, retrieve the sanitized value.
E. Return the sanitized comment back to the user to demonstrate the change.

Q31. Coding Problem

(Unit III - Creating Middlewares):
Create a custom "Maintenance Mode" middleware.

A. Define a variable isMaintenanceMode = true.
B. Create a middleware function that checks this variable.
C. If true, send a 503 Service Unavailable status with a JSON message "Site under maintenance".
D. If false, allow the request to proceed to the next handler.
E. Create a test route /status that returns "System Operational" and apply the middleware globally.

Q32. Coding Problem

(Unit I - Node.js Modules):
Create a custom local module and use it.

A. Create a file mathUtils.js.
B. In mathUtils.js, export an object containing two functions: square(n) and random(min, max).
C. Create a main file app.js.
D. Import the local module.
E. Use the imported functions to generate a random number between 1 and 10, square it, and log the result.

Q33. Coding Problem

(Unit III - Socket Services in Node.js):
Create a Socket.IO server that handles user typing indicators.

A. Server: Listen for a 'typing' event from a client.
B. Server: Broadcast a 'userTyping' event to all other connected clients (excluding the sender).
C. Server: Listen for 'stopTyping' and broadcast 'userStoppedTyping'.
D. Use socket.broadcast.emit specifically for this task.
E. Log to the server console whenever a typing event starts or stops.

Q34. Coding Problem

(Unit IV - Introduction to Mongoose):
Demonstrate how to query specific fields (Projection) and sort results in Mongoose.

A. Assume a Product model exists with fields: name, price, category, stock.
B. Create an async function getCheapProducts().
C. Find all products where price is less than 50.
D. Select ONLY the name and price fields (exclude _id if possible, or just include specific fields).
E. Sort the results by price in ascending order and log them.

Q35. Coding Problem

(Unit V - Introduction to PostgreSQL):
Write a script to handle SQL constraints/errors gracefully.

A. Create a table users with email as a UNIQUE column.
B. Insert a user with email "test@example.com".
C. Immediately try to insert another user with the exact same email.
D. Catch the error.
E. Check if the error code matches the PostgreSQL unique violation code ('23505') and log "Email already exists". For any other error, log "Unknown Error".

Q36. Coding Problem

(Unit VI - Testing and Deployment):
Simulate a third-party API rendering scenario.

A. Create an Express route /weather.
B. Inside the route, simulate a fetch to a third-party Weather API (mock the data: { temp: 25, city: 'London' }).
C. Construct an HTML string (Server Side Rendering) that embeds this data: <h1>Weather in London</h1><p>Temperature: 25C</p>.
D. Send this HTML string as the response.
E. Ensure the content type is set to text/html.

Q37. Coding Problem

(Unit I - Handling Data I/O in Node.js):
Work with Node.js Buffer class.

A. Create a Buffer from the string "Hello World".
B. Convert the buffer to Base64 format and log it.
C. Modify the first byte of the original buffer to match the ASCII code for 'Y'.
D. Convert the modified buffer back to a string.
E. Log the final string (Should read "Yello World").

Q38. Coding Problem

(Unit III - Creating Middlewares):
Implement a middleware that validates a custom API Key header.

A. Create a middleware validateApiKey.
B. Retrieve the value of the header x-api-key.
C. Compare it against a hardcoded secret "12345".
D. If it matches, call next().
E. If it fails, return status 401 and JSON { error: "Unauthorized" }.
F. Mount this middleware only on routes starting with /api.

Q39. Coding Problem

(Unit VI - Testing and Deployment):
Simulate a GitHub Actions workflow YAML generation (Concept Check).

A. You are required to deploy a Node.js app using GitHub.
B. Write a Javascript string that contains the content of a basic .github/workflows/node.js.yml file.
C. The YAML content must include: Trigger on push to 'main', runs-on 'ubuntu-latest', steps to checkout code, setup Node.js version 16, install dependencies (npm ci), and run tests (npm test).
D. Log this string to the console.

Q40. Coding Problem

(Unit II - Implementing HTTP Services):
Manually parse a JSON Request Body in a native HTTP server (No Express).

A. Create a server.
B. Listen for POST requests.
C. Collect data chunks from req into an array.
D. On req 'end', concatenate chunks and convert to string.
E. Parse the string as JSON. If successful, respond with the parsed object's message property in uppercase. If parsing fails, return 400.