MODULE II
EXPERIMENT 1
AIM:
To demonstrate the use of Standard callback pattern
Create a text file named input.txt with the following content :
Tutorials Point is giving self learning content to
teach the world in simple and easy way!!!!!
Create a js file named main.js with the following code :
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString()); console.log("Program Ended");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
Tutorials Point is giving self learning content to
teach the world in simple and easy way!!!!!
Program Ended
AIM:
To demonstrate the event emitter pattern .
Create an event emitter instance and register a couple of callbacks
const myEmitter = new EventEmitter();
function c1() { console.log('an
event occurred!');
}
function c2() {
console.log('yet another event occurred!');
}
1
myEmitter.on('eventOne', c1); // Register for eventOne
myEmitter.on('eventOne', c2); // Register for eventOne
When the event „eventOne‟ is emitted, both the above callbacks should
be invoked.
myEmitter.emit('eventOne');
The output in the console will be as follows:
an event occurred! yet
another event occurred!
AIM:
To demonstrate the use of defer execution of a function
// get the reference of EventEmitter class of events module
var events = require('events');
//create an object of EventEmitter class by using above reference
var em = new events.EventEmitter();
//Subscribe for FirstEvent
em.on('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});
// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
AIM:
To demonstrate the use stop execution of a function Objective:
Using process.exit() method stop function execution
var thisIsTrue = false;
exports.test = function(request, response, cb){
if (thisIsTrue) {
response.send('All is good!');
cb(null, response)
} else {
response.send('ERROR! ERROR!');
2
return cb("THIS ISN'T TRUE!");
}
console.log('I do not want this to happen. If there is an error.');
AIM:
To demonstrate the use Block escape event loop
const fs = require('fs');
function someAsyncOperation(callback) { //
Assume this takes 95ms to complete
fs.readFile('/path/to/file', callback);
}
const timeoutScheduled = Date.now();
setTimeout(() => {
const delay = Date.now() - timeoutScheduled;
console.log(`${delay}ms have passed since I was scheduled`);
}, 100);
// do someAsyncOperation which takes 95 ms to complete
someAsyncOperation(() => {
const startCallback = Date.now();
// do something that will take 10ms... while (Date.now() -
startCallback < 10) {
// do nothing
}
});
MODULE III
EXPERIMENT 1
AIM:
To demonstrate the Fs module file paths
3
// Require the given module
var fs = require('fs');
// Use statSync() method to store the returned
// instance into variable named stats
var stats =
fs.statSync("/Users/divyarani/Documents/geekforgeeks/geeks.js");
// Use isFile() method to log the result to screen
console.log('is file ? ' + stats.isFile());
var stats = fs.statSync("/Users/divyarani/Documents/geekforgeeks/geek");
// Use isDirectory() method to log the result to screen
console.log('is directory ? ' + stats.isDirectory());
Output
is file ? true is
directory ? true
AIM:
To demonstrate the how to read, write, & close file
app.js
var fs = require("fs");
fs.readFile("temp.txt", function(err, buf) {
console.log(buf.toString());
});
Create a temp.txt within the same directory and write in it anything
you‟d like. Run your script using node app.js and you should see in the
console the contents of your file.
var fs = require("fs");
This line does the job of importing the fs package and allowing us to utilize
it within our own code.
fs.readFile("temp.txt", function(err, buf) { console.log(buf);
});
AIM:
Demonstrate how to read data in SQL using node js
The following select.js program selects all data from the todos table of the
todoapp database:
4
let mysql = require('mysql'); let
config = require('./config.js');
let connection = mysql.createConnection(config);
let sql = `SELECT * FROM todos`;
connection.query(sql, (error, results, fields) => {
if (error) {
return console.error(error.message);
}
console.log(results);
});
connection.end();
Let‟s run the select.js program.
>node select.js
[ RowDataPacket { id: 1, title: 'Learn how to insert a new row', completed: 1
},
RowDataPacket { id: 2, title: 'Insert a new row with placeholders',
completed:0 },
RowDataPacket { id: 3, title: 'Insert multiple rows at a time', completed:
0 },
RowDataPacket { id: 4, title: 'It should work perfectly', completed: 1 } ]
It returned 4 rows as expected.
The following select2.js program selects only completed todo:
let mysql = require('mysql'); let
config = require('./config.js');
let connection = mysql.createConnection(config);
let sql = `SELECT * FROM todos WHERE
completed=?`; connection.query(sql, [true], (error, results,
fields) => { if (error) {
return console.error(error.message);
}
console.log(results);
});
connection.end();
5
>node select2.js
[ RowDataPacket { id: 1, title: 'Learn how to insert a new row', completed:
1 },
RowDataPacket { id: 4, title: 'It should work perfectly', completed: 1 } ]