CSA-301 Full Stack Development
Ms. Myrtle Fernandes, Ms. S. Gajalaxmi
Fr. Agnel College of Arts & Commerce, Pilar
Week 4:
• Promises, Promise Chaining
• Command Line Arguments
• Working with the File System, Reading Files, Writing Files
Lab Exercises:
1) To create a Promise with Asynchronous code, using of promise’s then() method.
1_Promises.js
var fs = require('fs');
var promise = new Promise(function (resolve, reject) {
[Link]('[Link]', 'utf8', function (error, data) {
if (error) {
return reject(error);
}
resolve(data);
});
});
[Link](function (result) {
[Link](result);
}, function (error) {
[Link]([Link]);
});
Output:
Run the script as follows:
>node 1_Promises.js
After executing the script, file contents should be displayed.
2) Demonstrating Promise Chaining
2_PromiseChaining.js
let promise = new Promise(function(resolve, reject) {
const user = {
name: 'ABC XYZ',
email: 'nouser@[Link]',
password: 'abc'
};
resolve(user);
});
[Link](function(user) {
[Link](`Got user ${[Link]}`);
// Return a simple value
return [Link];
}).then(function(email) {
[Link](`User email is ${email}`);
});
Output:
Run the script as follows:
>node 2_PromiseChaining.js
After executing the script, it will print below:
Got user ABC XYZ
User email is nouser@[Link]
3) Demonstrating handling rejections in Promise using catch()
3_PromisesChainingUsingCatch.js
/*Demonstrating handling rejections in Promise using catch() method
The code will behave as though the catch() callback were passed as the
second callback to then(), but is more convenient for chaining.
In the event that the promise is rejected, the catch() callback will
display the error message.*/
var fs = require('fs');
var promise = new Promise(function (resolve, reject) {
[Link]('[Link]', 'utf8', function (error, data) {
if (error) {
return reject(error);
}
resolve(data);
});
});
[Link](function (result) {
[Link](result);
return 'THE END!';
}).catch(function (error) {
[Link]([Link]);
});
Output:
Run the script as follows:
>node 3_PromisesChainingUsingCatch.js
After executing the script, file contents should be displayed.
4) Demonstrating promise interleaving then, catch and finally in a chain
4_PromisesChainingCatchfinally.js
/* Promise- Interleaving then, catch and finally in a chain*/
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
let success = true; // true for resolved and false for rejection
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Error fetching data.");
}
}, 2000);
});
[Link]((message) => {
[Link]("Success:", message);
}).catch((error) => {
[Link]("Error:", error);
}).finally(() => {
[Link]("Promise settled (fulfilled or rejected).");
});
Output:
Run the script as follows:
>node 4_PromisesChainingCatchfinally.js
After executing the script, it will print below:
Success: Data fetched successfully!
Promise settled (fulfilled or rejected).
5) Demonstrating accessing command line arguments using [Link]-foreach()
5_CommandLineArgs.js
/*Accessing command line arguments using [Link].
Using foreach method to iterate the command line arguments*/
/*Note that the first two elements of this array are the node
executable,
followed by the name of the invoked JavaScript file.
This means that the actual application arguments begin at
[Link][2]. */
[Link](function (value, index, args) {
[Link]('[Link][' + index + '] = ' + value);
});
Output:
Run the script as follows:
>node 5_CommandLineArgs.js
After executing the script, it will print below:
[Link][0] = C:\Program Files\nodejs\[Link]
[Link][1] = C:\Week4Project\5_commandlineargs.js
6) Demonstrating accessing command line arguments using [Link]-slice()
6_CommandLineArgs.js
/*Accessing command line arguments using [Link] slice method
to start slicing from a given index. The result of slice()
will store the elements in an array.
Further we perform addition on the given numbers.*/
//slice method starts taking values from the 2nd index since
// first two arguments are node and filename
const args = [Link](2);
// Check if two arguments are provided
if ([Link] !== 2) {
[Link]("Usage: node <currentFileName> <num1> <num2>");
[Link](1);
}
// Convert arguments to numbers
const num1 = parseFloat(args[0]);
const num2 = parseFloat(args[1]);
// Validate input
if (isNaN(num1) || isNaN(num2)) {
[Link]("Both arguments must be valid numbers.");
[Link](1);
}
// Add and display the result
const sum = num1 + num2;
[Link](`The sum of ${num1} and ${num2} is ${sum}`);
Output:
Run the script as follows:
> node 6_CommandLineArgs.js 20 40
After executing the script, it will print below:
The sum of 20 and 40 is 60
7) Accessing command line arguments using [Link] to add a list of numbers
given through command line arguments.
7_CommandLineArgs.js
/*Accessing command line arguments using [Link] to add a list of
numbers given through command line arguments*/
/*All command line arguments passed to a Node application are
available via the [Link] array and printed to the
console using the forEach() method.*/
/*Note that the first two elements of this array are the node
executable,
followed by the name of the invoked JavaScript file.
This means that the actual application
arguments begin at [Link][2]. */
[Link](function (value, index, args) {
// Skip the first two default arguments
if (index < 2) return;
// Convert the argument to a number
const num = parseFloat(value);
// Initialize [Link] if it doesn't exist
if (![Link]) {
[Link] = 0;
// Add to the total if it's a valid number
if (!isNaN(num)) {
[Link] += num;
}
});
// Print the result using the args array
[Link]("Sum of numbers:", [Link]);
Output:
Run the script as follows:
> node 7_CommandLineArgs.js 10 20 30 40 50 60 70
After executing the script, it will print below:
Sum of numbers: 280
8) Demonstrating working with File System using __filename and __dirname
8_FileSystem.js
/*Demonstrating working with File System-Using __filename and __dirname
to print file paths.
Also to display and change the current working directory*/
[Link]('Currently executing file is ' + __filename);
[Link]('It is located in ' + __dirname);
[Link]('Current working directory is in ' + [Link]());
try {
[Link]('/');
} catch (error) {
[Link]('chdir: ' + [Link]);
}
[Link]('Current working directory is now ' + [Link]());
Output:
Run the script as follows:
> node 8_FileSystem.js
After executing the script, it will print below:
It is located in C:\Week4Project
Current working directory is in C:\Week4Project
Current working directory is now C:\
9) Demonstrating readFile() with and without encoding
9_ReadFile_Encoding_WithoutEncoding.js
var fs = require('fs');
[Link](__filename, function (error, data) {
if (error) {
return [Link]([Link]);
}
[Link]("Printing without encoding:")
[Link](data);
});
[Link](__filename, "utf8", function (error, data) {
if (error) {
return [Link]([Link]);
}
[Link]("Printing by encoding:")
[Link](data);
});
Output:
Run the script as follows:
> node 9_ReadFile_Encoding_WithoutEncoding.js
After executing the script, it will print below:
Printing without encoding:
<Buffer 76 61 72 20 66 73 20 3d 20 72 65 71 75 69 72 65 28 27 66 73 27 29 3b 0d 0a
66 73 2e 72 65 61 64 46 69 6c 65 28 5f 5f 66 69 6c 65 6e 61 6d 65 2c 20 66 ... 372
more bytes>
Printing by encoding:
var fs = require('fs');
[Link](__filename, function (error, data) {
if (error) {
return [Link]([Link]);
}
[Link]("Printing without encoding:")
[Link](data);
});
[Link](__filename, "utf8", function (error, data) {
if (error) {
return [Link]([Link]);
}
[Link]("Printing by encoding:")
[Link](data);
});
10) Demonstrating asynchronous file reading using readFile()
10_ReadFileAsynchronously.js
/*Asynchronously reading a file using a callback function.*/
var fs = require('fs');
[Link]('[Link]', 'utf8', function (error, data) {
if (error) {
return [Link](error);
}
[Link](data);
});
[Link]("End of code");
Output:
Run the script as follows:
> node 10_ReadFileAsynchronously.js
After executing the script, it will print below:
End of code
<<text from file>>
11) Demonstrating Synchronous file reading using readFileSync()
11_ReadFileSynchronously.js
/*Synchronously reading a file.*/
var fs = require('fs');
try {
var data = [Link]('[Link]', 'utf8');
[Link](data);
} catch (error) {
[Link](error);
}
[Link]("End of code");
Output:
Run the script as follows:
> node 11_ReadFileSynchronously.js
After executing the script, it will print below:
<<text from file>>
End of code
12) Demonstrating asynchronous writing into a file using WriteFile(). Also
demonstrated usage of flag wx.
12_WriteFileAsynchronously.js
/*Writing data to a file using Asynchronous file writeFile().
Udage of writeFile() with and without flag demonstrated*/
var fs = require('fs');
var data = 'This is my BCA file content.';
//writeFile() will create a new file, or overwrite an existing file
with the same name.
[Link](__dirname + '/[Link]', data, function (error) {
if (error) {
return [Link]([Link]);
}
});
//passing the flag wx causes an error to be thrown if the file already
exists,
// while the a flag causes data to be appended to an existing file
instead of overwriting.
[Link](__dirname + '/[Link]', data, {
flag: 'wx'
}, function (error) {
if (error) {
return [Link]([Link]);
}
});
Output:
Run the script as follows:
> node 12_WriteFileAsynchronously.js
After executing the script, it will create a file [Link] with given file contents if file is
not present. If [Link] is present, it will overwrite it.
The second writefile in [Link] will create the file with given file contents if file is
not present. If [Link] is present, it will throw an error.
13) Demonstrating Synchronous writing into a file using WriteFileSync()
13_WriteFileSynchronously.js
/*Synchronously writing into a file.*/
var fs = require('fs');
try {
// Synchronous function: writeFileSync throws exceptions that can
be caught
[Link]('[Link]', 'This is some sample content written
synchronously.', 'utf8');
[Link]('File written successfully.');
} catch (error) {
[Link]('Error writing to file:', error);
}
[Link]("End of code");
Output:
Run the script as follows:
> node 13_WriteFileSynchronously.js
File written successfully.
End of code