Lecture 7 - NodeJs
Lecture 7 - NodeJs
1. Which of the following is NOT a core module in Node.js? a) fs b) http c) path d) react
Answer: d) react - React is a front-end library, not a core Node.js module. The fs, http,
and path are all built-in core modules in Node.js.
1. What does the Node.js module system primarily use to export functionality? a)
window.exports b) module.exports c) exports.module d) node.export
1. Which command is used to initialize a new Node.js project? a) node init b) npm
start c) npm init d) node create
Answer: c) npm init - This command creates a new package.json file for a Node.js
project.
State Questions
1. State the difference between synchronous and asynchronous file operations in
Node.js.
Answer: Synchronous file operations in Node.js block the execution of code until the
operation completes. They are executed in sequence and can make the application
unresponsive if the operation takes a long time. Functions like fs.readFileSync() are
examples of synchronous operations.
Asynchronous file operations, on the other hand, don't block the execution flow. They
use callbacks, promises, or async/await to handle the result when the operation
completes, allowing the program to continue executing other code in the meantime.
Functions like fs.readFile() are examples of asynchronous operations. Asynchronous
operations are preferred in Node.js to maintain performance and responsiveness,
especially for I/O-bound operations.
1. State what middleware is in the context of Express.js and how it's used.
Answer: Middleware in Express.js are functions that have access to the request object
(req), the response object (res), and the next middleware function in the application's
request-response cycle. These functions can execute any code, modify request and
response objects, end the request-response cycle, or call the next middleware function.
Middleware is used for tasks such as: - Parsing request bodies - Logging requests -
Authentication and authorization - Error handling - Serving static files - CORS handling
Middleware is applied using the app.use() method or can be specific to particular HTTP
methods and routes. The order of middleware registration is important as they are
executed sequentially.
1. State the purpose of the Node Package Manager (NPM) in Node.js development.
Answer: The Node Package Manager (NPM) is the default package manager for Node.js
and serves several key purposes:
NPM has become essential for modern JavaScript development, making it easy to reuse
code and integrate with the broader JavaScript ecosystem.
1. State what the Event Loop is in Node.js and why it's important.
Answer: The Event Loop is a core mechanism in Node.js that enables non-blocking I/O
operations despite JavaScript being single-threaded. It works by offloading operations
to the system kernel whenever possible and putting callback functions into a queue to
be executed after the current code completes.
The Event Loop continuously checks if there are any callbacks in the queue that need to
be executed. When the call stack is empty, it takes the first event from the queue and
pushes it to the call stack, which runs it.
Answer:
import is the newer ECMAScript Modules (ESM) syntax: - It is static and loads modules
at parse time - It must be used at the top level of the file (outside of any blocks) - It
cannot be used conditionally - It has more features like named imports, default imports,
and namespace imports - Syntax: import module from './module' or import
{ namedExport } from './module'
Node.js supports both systems, but ESM is considered more modern and is the standard
for JavaScript modules going forward. To use ESM in Node.js, you need to either use
the .mjs file extension or set "type": "module" in your package.json.
const fs = require('fs');
console.log('Start');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) console.log('Error');
else console.log('File read');
});
console.log('End');
The output will be "Start", then "End", and then either "Error" or "File read" depending
on whether the file exists and can be read. This demonstrates the asynchronous nature
of fs.readFile(), which doesn't block the execution flow. The callback function is
executed after the file operation completes, which happens after "End" is logged.
const os = require('os');
console.log(os.platform());
// Assuming the code runs on a Windows machine
Answer: win32 - The os.platform() method returns a string identifying the operating
system platform. On Windows, it returns 'win32' regardless of whether the system is 32-
bit or 64-bit.
Answer: /path - The url.parse() method parses a URL string into an object with
properties. The pathname property contains the path portion of the URL, which is '/path'
in this case.
eventEmitter.on('test', () => {
console.log('Test event fired');
});
console.log('Before emit');
eventEmitter.emit('test');
console.log('After emit');
The code first logs "Before emit", then emits the 'test' event which triggers the callback
function that logs "Test event fired", and finally logs "After emit". This demonstrates the
synchronous nature of the event emitter in Node.js.
server.listen(3000, () => {
console.log('Server running on port 3000');
});
Answer: The response is never ended. After writing to the response, you need to call
res.end() to signal that the response is complete. Corrected code: ```javascript const
http = require('http');
const fs = require('fs');
fs.readFile('file.txt', (data, err) => {
if (err) {
console.error(err);
return;
}
console.log(data.toString());
});
Answer: The callback parameters are in the wrong order. The error parameter should
come first, followed by the data parameter. Corrected code: ```javascript const fs =
require('fs');
app.listen(3000);
Answer: There's no error in the syntax, but it's a best practice to include a callback
function with app.listen() to confirm the server has started successfully. Improved code:
```javascript const express = require('express'); const app = express();
app.get('/users', (req, res) => { const users = ['John', 'Jane', 'Bob']; res.send(users); });
Answer: The variable name used in the console.log statement (directory) doesn't match
the variable that was declared (dirname). Corrected code: javascript const path =
require('path'); const filePath = 'C:\\Users\\username\\documents\\file.txt'; const
dirname = path.dirname(filePath); console.log('Directory: ' + dirname);
// Create HTTP server const server = http.createServer((req, res) => { // Set the response
HTTP header with HTTP status and Content type res.writeHead(200, {'Content-Type':
'text/plain'});
});
1. Complete the following Node.js code to read a file asynchronously and log its
contents:
const fs = require('fs');
1. Write Node.js code to create a basic Express.js application with a route that returns
a JSON response.
// Define a route that returns JSON app.get('/api/data', (req, res) => { const data = {
message: 'Success', items: [ { id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, { id: 3, name:
'Item 3' } ], timestamp: new Date() };
res.json(data);
});
// Set up a listener for the 'data' event myEmitter.on('data', (data) => { console.log('Data
received:', data); });
// Emit a 'data' event with some data console.log('About to emit data event');
myEmitter.emit('data', { id: 123, name: 'Sample Data', timestamp: new Date() });
console.log('Event emitted'); ```
1. Write Node.js code to create a module that exports a function to calculate the
factorial of a number, and then import and use that module.
Answer:
Then, create a file to import and use the module: ```javascript // app.js const factorial =
require('./factorial');