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

Node Js

The document provides an overview of Node.js, including its components like NPM, REPL, and modules. It outlines various coding examples for file operations, database connections, and server creation, as well as comparisons between AngularJS and Node.js. Additionally, it discusses features of Node.js, the purpose of module.exports, and the differences between GET and http.request() methods.

Uploaded by

yh5292934
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)
13 views9 pages

Node Js

The document provides an overview of Node.js, including its components like NPM, REPL, and modules. It outlines various coding examples for file operations, database connections, and server creation, as well as comparisons between AngularJS and Node.js. Additionally, it discusses features of Node.js, the purpose of module.exports, and the differences between GET and http.request() methods.

Uploaded by

yh5292934
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

a) What are the components of NPM?

Website: Allows browsing of packages.​


Command Line Interface (CLI): Helps install, update, and manage packages.​
Registry: Central repository of Node.js packages.​
b) Syntax to read a file asynchronously in Node.js using the fs module

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {

if (err) throw err;


console.log(data);
});
c) Syntax for configuring a database connection in a Node.js application:
const mysql = require('mysql');
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydb'
});
con.connect(err => {
if (err) throw err;
console.log('Connected!');
});
d) What is NodeJS?​
Node.js is an open-source, cross-platform JavaScript runtime environment that
executes JavaScript code outside a web browser.

e) What is REPL?​
REPL stands for Read-Eval-Print Loop. It is a simple, interactive shell that processes
Node.js expressions.

f) Define Anonymous function​


An anonymous function is a function without a name, often used as arguments to other
functions.

g) Features of Node Js: Asynchronous and event-driven, Fast execution with


V8 engine, Single-threaded but scalable , No buffering​
h) Arrow function:​
Shorter syntax for writing functions: const add = (a, b) => a + b;

i) Types of streams in NodeJs:

Readable. Writable. Duplex. Transform​


j) What is a module? List its types:​
A module is a reusable block of code.​
Types:Built-in modules (e.g., fs, http)​
Local modules​
Third-party modules​
a) Node Js program to create a Historical Place portal:

const http = require('http');

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


res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Welcome to Historical Places of India</h1>');
}).listen(3000);
b) Update student marks and display result:

const mysql = require('mysql');

const con = mysql.createConnection({

host: 'localhost',

user: 'root',
password: '',
database: 'school'
});
con.connect(err => {
if (err) throw err;
let sql = "UPDATE student SET marks = 90 WHERE rno = 1";
con.query(sql, (err, result) => {
if (err) throw err;
console.log("Records updated: " + result.affectedRows);
});
});
c) Purpose of module.exports in Node.js:​
It is used to export functions, objects, or variables from a module so they can be used
in other files.

d) AngularJS vs NodeJS:

Feature AngularJS NodeJS

Type Frontend Backend runtime


framework environment

Languag JavaScript JavaScript


e

Use Dynamic web Server-side scripting


Case apps

e) What is a listener? Explain requestListener():​


A listener is a function that waits for an event to occur.​
Example:

const http = require('http');


const server = http.createServer((req, res) => {
res.end("Hello World");
});
server.listen(3000);
a) Traditional Web Server Model:
One thread per request​
Blocking I/O operations​
Limitations: Scalability issues​
High memory usage​
b) Convert “SY BBA - CA” to upper and lower case:
const str = "SY BBA - CA";
console.log(str.toUpperCase());
console.log(str.toLowerCase());
c) File System Operations:​
The file system module (fs) allows you to:Read/write files​
Rename files. Delete files. Append data​
d) What is an event? Methods: Event is an action that the server listens to. B
Two methods:on(event, listener) bnemit(eventName, args...)​
e) Write to file (sync and async):
const fs = require('fs');

// Synchronous
fs.writeFileSync('sync.txt', 'Hello sync');

// Asynchronous
fs.writeFile('async.txt', 'Hello async', (err) => {
if (err) throw err;
console.log('Written asynchronously');
});
a) Create Customer DB and Account Table:
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: ""
});
con.connect(err => {
if (err) throw err;
con.query("CREATE DATABASE customerDB", (err) => {
if (err) throw err;
con.changeUser({database: 'customerDB'}, () => {
const sql = "CREATE TABLE account (cid INT, name VARCHAR(255), balance
FLOAT)";
con.query(sql, (err) => {
if (err) throw err;
console.log("Table created");
});
});
});
});

b) Buffer Operations:

const buf1 = Buffer.from('Hello');


const buf2 = Buffer.from('World');
const buf3 = Buffer.concat([buf1, buf2]);
console.log(buf3.toString());
const slice = buf1.slice(0, 2);
console.log(slice.toString());
console.log(Buffer.compare(buf1, buf2)); // returns 0 if same
c) What is a package in NodeJS? A package is a reusable module published to the
NPM registry. Example: npm install express

d) Search word in a file:

const fs = require('fs');
const word = "Node";
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
if (data.includes(word)) {
console.log(`${word} found`);
} else {
console.log(`${word} not found`);
}
});

e) Dependencies vs devDependencies:

Dependencies: Needed in production (express, mysql)​


devDependencies: Needed only in development (nodemon, mocha)​

Q5) Answer the following (Any Two) : [2 × 3 = 6]

a) Web Server in Detail:​


A web server handles HTTP requests and sends responses to clients.​
Node.js can create a lightweight web server using the http module.

b) Blocking vs Non-blocking:

Blocking Non-blocking

Waits till task completes Moves to next task


immediately

Slower for concurrent Efficient and fast


tasks

c) Usage of Buffer Class:​


Buffer is used for binary data manipulation.​
Example:
const buf = Buffer.from('Hello');
console.log(buf.toString()); // Output: Hello

Let me know if you want these formatted into a PDF or used in a practice test!

set 2

Here's the complete solution for the Node.js question paper (S.Y. B.B.A. C.A.
Semester IV):

Q1) Answer the following (Any Eight): [8×2=16]

a) What is REPL in Node.js?​


REPL stands for Read-Eval-Print Loop. It is a CLI (command-line interface)
environment provided by Node.js where you can execute JavaScript code interactively.

b) NPM stands for?​


NPM stands for Node Package Manager.

c) What do you mean by event in Node.js?​


An event in Node.js refers to an action or occurrence (like a connection or a file
opening) to which the application can respond using event listeners.

d) What is the use of prompt-sync module?​


The prompt-sync module is used to take user input synchronously from the
command line in Node.js.

e) Define Anonymous function.​


An anonymous function is a function without a name, often used as a callback.​
Example:

let x = function(a, b) { return a + b; };

f) Explain global packages from Node.js.​


Global packages are Node.js packages installed using the -g flag and are available
system-wide, not just in a single project.
g) What is express.js?​
Express.js is a minimal and flexible Node.js web application framework that
provides features to build web and mobile applications easily.

h) Write syntax to create Buffer?

let buf = Buffer.from('Hello');

i) Which command is used for deleting a file?

fs.unlink('filename', callback);

Q2) Answer the following (Any Four): [4×4=16]

a) What is Node.js? Explain the features of Node.js.​


Node.js is a JavaScript runtime environment that allows executing JS code on the
server-side.

Features:Asynchronous and Event-driven​


Very Fast​
Single-threaded but highly scalable​
No Buffering​
Open source and cross-platform​
b) How we can create a local module with example?​
Create myModule.js:

exports.sayHello = function() {
return "Hello from Module!";
};
In main.js:
let myModule = require('./myModule');
console.log(myModule.sayHello());

c) What is package.json File?​


package.json is the metadata file of a Node.js project. It includes project info,
dependencies, scripts, and versioning.

d) Explain Node.js process model?​


Node.js uses a single-threaded, non-blocking I/O process model. It handles multiple
requests using event-driven architecture without creating multiple threads, which makes
it highly efficient.
e) Write down Advantages of NPM.

Easy to install and manage packages​


Access to thousands of libraries​
Supports versioning and dependency management​
Can install both globally and locally

a) Explain module.exports in Node.js?​


module.exports is used to export functions, objects, or variables from a module
to be used in other files.

b) Write steps to load core modules in Node.js?

1.​ Use require() method.​

2.​ Example:​

let http = require('http');

c) How to write synchronous data to File explain with suitable example.

const fs = require('fs');
fs.writeFileSync('data.txt', 'This is written synchronously');

d) Write a code for selecting all records from the “employee” table.

const mysql = require('mysql');


const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'test'
});
con.connect((err) => {
if (err) throw err;
con.query("SELECT * FROM employee", (err, result) => {
if (err) throw err;
console.log(result);
});
});
e) Using Node.js create a webpage to read two file names from user and combine
in third file.

const fs = require('fs');
const prompt = require('prompt-sync')();
let file1 = prompt('Enter first file: ');
let file2 = prompt('Enter second file: ');
let data1 = fs.readFileSync(file1, 'utf8');
let data2 = fs.readFileSync(file2, 'utf8');
fs.writeFileSync('combined.txt', data1 + data2);
console.log('Files combined!');

a) Write down the difference between GET and http.request() method?

GET Method http.request()

Simplified HTTP GET Used for more complex


request requests

Only GET supported Supports other HTTP


methods

Uses http.get() Uses http.request()

b) What is the use of fs.ftruncate method?​


fs.ftruncate() is used to truncate the size of an opened file. It modifies the
length of the file.

c) Write Node.js application to create user-defined Rectangle module.​


rectangle.js:

exports.area = function(width, height) {


return width * height;
};
app.js:
let rect = require('./rectangle');
console.log("Area: " + rect.area(10, 5));

You might also like