0% found this document useful (0 votes)
6 views9 pages

Lecture 7 - NodeJs

Lecture 7 covers Node.js fundamentals including its definition, core modules, and the module system. It explains synchronous vs asynchronous file operations, middleware in Express.js, the purpose of NPM, and the Event Loop's significance. The lecture also includes code examples, error handling, and creating a basic HTTP server and Express.js application.

Uploaded by

moarcarc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views9 pages

Lecture 7 - NodeJs

Lecture 7 covers Node.js fundamentals including its definition, core modules, and the module system. It explains synchronous vs asynchronous file operations, middleware in Express.js, the purpose of NPM, and the Event Loop's significance. The lecture also includes code examples, error handling, and creating a basic HTTP server and Express.js application.

Uploaded by

moarcarc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Lecture 7 - NodeJs

Multiple Choice Questions


1. What is Node.js? a) A JavaScript framework for building mobile applications b) A
JavaScript runtime environment built on Chrome's V8 JavaScript engine c) A
programming language derived from JavaScript d) A database management
system

Answer: b) A JavaScript runtime environment built on Chrome's V8 JavaScript


engine - Node.js allows JavaScript to be run outside of a browser environment.

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

Answer: b) module.exports - In Node.js, functionality is exported from a module using


module.exports or its shorthand exports.

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.

1. What is the purpose of package.json in a Node.js application? a) To store


application source code b) To manage project metadata and dependencies c) To
configure database connections d) To define server routes

Answer: b) To manage project metadata and dependencies - The package.json file


contains metadata about the project and lists its dependencies.

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:

• It allows developers to install, share, and manage dependencies (third-party


packages/modules)
• It provides a command-line interface to interact with the npm registry
• It manages project metadata and configuration through the package.json file
• It enables version management of dependencies
• It facilitates publishing and distribution of Node.js packages
• It provides scripts functionality to automate development tasks
• It helps in managing project dependencies both globally and locally

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.

The Event Loop is important because: - It allows Node.js to handle thousands of


concurrent connections with a single thread - It enables asynchronous programming,
making Node.js highly efficient for I/O-bound operations - It prevents blocking of the
main thread, keeping applications responsive - It's what makes Node.js particularly well-
suited for real-time applications and APIs

1. State the difference between require() and import statements in Node.js.

Answer:

require() is the original CommonJS module system used in Node.js: - It is synchronous


and loads modules at runtime - It can be called anywhere in the file - It can be used
conditionally (inside if statements, etc.) - It returns whatever was assigned to
module.exports - Syntax: const module = require('./module')

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.

Code Output Questions


1. What is the output of the following Node.js code?

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');

Answer: Start End Error or Start End File read

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.

1. What is the output of the following Node.js code?

const path = require('path');


const filePath = path.join('/home', 'user', 'documents', 'file.txt');
console.log(filePath);

Answer: /home/user/documents/file.txt - The path.join() method joins all given path


segments together using the platform-specific separator as a delimiter, then normalizes
the resulting path.

1. What is the output of the following Node.js code?

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.

1. What is the output of the following Node.js code?

const url = require('url');


const myUrl = url.parse('https://example.com/path?query=123');
console.log(myUrl.pathname);

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.

1. What is the output of the following Node.js code?


const events = require('events');
const eventEmitter = new events.EventEmitter();

eventEmitter.on('test', () => {
console.log('Test event fired');
});

console.log('Before emit');
eventEmitter.emit('test');
console.log('After emit');

Answer: Before emit Test event fired 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.

Find Errors Questions


1. Find and fix the error in the following Node.js code:

const http = require('http');

const server = http.createServer((req, res) => {


res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
});

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 server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/


plain'}); res.write('Hello World!'); res.end(); // Add this line to end the response });

server.listen(3000, () => { console.log('Server running on port 3000'); }); ```

1. Find and fix the error in the following Node.js code:

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');

fs.readFile('file.txt', (err, data) => { if (err) { console.error(err); return; }


console.log(data.toString()); }); ```

1. Find and fix the error in the following Node.js code:

const express = require('express');


const app = express();

app.get('/users', (req, res) => {


const users = ['John', 'Jane', 'Bob'];
res.send(users);
});

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); });

app.listen(3000, () => { console.log('Server running on port 3000'); }); ```

1. Find and fix the error in the following Node.js code:

const path = require('path');


const filePath = 'C:\\Users\\username\\documents\\file.txt';
const dirname = path.dirname(filePath);
console.log('Directory: ' + directory);

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);

1. Find and fix the error in the following Node.js code:

const events = require('events');


const eventEmitter = events.EventEmitter();

eventEmitter.on('message', (msg) => {


console.log(msg);
});

eventEmitter.emit('message', 'Hello World!');

Answer: EventEmitter is a constructor and needs to be instantiated with the 'new'


keyword. Corrected code: ```javascript const events = require('events'); const
eventEmitter = new events.EventEmitter();

eventEmitter.on('message', (msg) => { console.log(msg); });

eventEmitter.emit('message', 'Hello World!'); ```

Write/Complete Code Questions


1. Write Node.js code to create a simple HTTP server that responds with "Hello,
World!" on port 3000.

Answer: ```javascript const http = require('http');

// 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'});

// Send the response body "Hello, World!"


res.end('Hello, World!');

});

// Listen on port 3000 server.listen(3000, () => { console.log('Server running at http://


localhost:3000/'); }); ```

1. Complete the following Node.js code to read a file asynchronously and log its
contents:
const fs = require('fs');

// Your code here

Answer: ```javascript const fs = require('fs');

// Read file asynchronously fs.readFile('example.txt', 'utf8', (err, data) => { if (err)


{ console.error('Error reading file:', err); return; } console.log('File contents:');
console.log(data); }); ```

1. Write Node.js code to create a basic Express.js application with a route that returns
a JSON response.

Answer: ```javascript const express = require('express'); const app = express();

// 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);

});

// Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () =>


{ console.log( Server running on port ${PORT} ); }); ```

1. Complete the following Node.js code to create a custom event emitter:

const events = require('events');

// Your code here to create an event emitter


// that emits a 'data' event with some data
// and listens for that event

Answer: ```javascript const events = require('events');

// Create a custom event emitter class MyEmitter extends events.EventEmitter {} const


myEmitter = new MyEmitter();

// 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:

First, create a file named factorial.js : ```javascript // factorial.js function factorial(n) { if


(n === 0 || n === 1) { return 1; } if (n < 0) { throw new Error('Factorial is not defined for
negative numbers'); } return n * factorial(n - 1); }

module.exports = factorial; ```

Then, create a file to import and use the module: ```javascript // app.js const factorial =
require('./factorial');

try { console.log( Factorial of 5: ${factorial(5)} );


console.log( Factorial of 0: ${factorial(0)} ); console.log( Factorial of 10: $
{factorial(10)} ); // Uncomment to see error handling // console.log( Factorial of -1: $
{factorial(-1)} ); } catch (error) { console.error('Error:', error.message); } ```

You might also like