WT U5 Node JS File System Module 17 June 2022
WT U5 Node JS File System Module 17 June 2022
var fs = require('fs');
Sample I/O:
Here fs.readFile() is a async function whose purpose is to
read a file. If an error occurs during the read operation,
then the err object will contain the corresponding error,
else data will contain the contents of the
file. readFile passes err and data to the callback function
after the read operation is complete, which finally prints
the content.
File Writing:
Syntax:
fs.writeFile(filename, data[, options], callback)
Sample I/O:
In previous slide, replace calc1 with calc and check, What is output?
Sample I/O:
Deleting a file:
Sample I/O:
Read Files
The fs.readFile() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as Node.js):
Create a Node.js file that reads the HTML file, and return the content:
demofile1.html
<html> var http = require('http');
<body> var fs = require('fs');
<h1>My Header</h1> http.createServer(function (req, res) {
<p>My paragraph.</p> fs.readFile('demofile1.html', function(err, data) {
</body> res.writeHead(200, {'Content-Type': 'text/html'});
</html> res.write(data);
return res.end();
});
}).listen(8080);
Difference between synchronous and asynchronous read:
Sample I/O:
Node.js - Event Emitter
Many objects in a Node emit events, for example, a net.Server emits an event each time a peer
connects to it, an fs.readStream emits an event when the file is opened. All objects which emit
events are the instances of events.EventEmitter.
EventEmitter Class:
EventEmitter class lies in the events module. It is accessible via the following code
When an EventEmitter instance faces any error, it emits an 'error' event. When a new listener is
added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is
fired.
EventEmitter provides multiple properties like on and emit.
on property is used to bind a function with the event and emit is used to fire an event.
Node.js Timer:
Node.js Timer functions are global functions. You don't need to use require() function
in order to use timer functions. Let's see the list of timer functions.
Set timer functions:
•setImmediate(): It is used to execute setImmediate.
•setInterval(): It is used to define a time interval.
•setTimeout(): ()- It is used to execute a one-time callback after delay milliseconds.
Clear timer functions:
•clearImmediate(immediateObject): It is used to stop an immediateObject, as
created by setImmediate
•clearInterval(intervalObject): It is used to stop an intervalObject, as created by
setInterval
•clearTimeout(timeoutObject): It prevents a timeoutObject, as created by
setTimeout
Node.js Timer setInterval() Example
Handling data I/O: Buffers
Node provides Buffer class which provides instances to store raw data similar to an array of
integers but corresponds to a raw memory allocation outside the V8 heap.
Buffer class is a global class that can be accessed in an application without importing the
buffer module.
Creating Buffers
Node Buffer can be constructed in a variety of ways.
Method 1
Following is the syntax to create an uninitiated Buffer of 10 octets −
var buf = new Buffer(10);
Method 2
Following is the syntax to create a Buffer from a given array −
var buf = new Buffer([10, 20, 30, 40, 50]);
Method 3
Following is the syntax to create a Buffer from a given string and optionally encoding type −
var buf = new Buffer("Simply Easy Learning", "utf-8");
Though "utf8" is the default encoding, you can use any of the following encodings "ascii", "utf8", "utf16le", "ucs2", "base64" or "hex".
Methods of writing and reading from Buffer objects are as below:
Method
buffer.write(string, [offset], [length], [encoding])
buffer[offset] = value
buffer.fill(value,[offset],[end])
writeInt8(value, offset, [noassert])
writeInt16LE(value, offset, [noassert])
writeInt16BE(value, offset, [noassert])
Syntax
Following is the syntax of the method to convert a Node Buffer into JSON object −
buf.toJSON()
Return Value
This method returns a JSON-representation of the Buffer instance.
Example
Property Description
href This is the full URL string that was originally parsed
protocol The request protocol lowercased
host The full host portion of the URL including port information
lowercased
auth The authentication information portion of a URL
hostname The hostname portion of the host lowercased
port The port number portion of the host
Pathname The path protion of the URL including the initial slash if present
search The query string portion of the URL including the leading question
mark
path The full path including the pathname and search
query This is either the parameter portion of the query string or a parsed
object containing the query string parameters and values if the
parseQueryString is set to true.
hash The hash portion of the URL including the pound sign(#)
Converting JSON text to JavaScript Object
A JSON object is a key-value data format that is typically rendered in curly braces.
JSON object consist of curly braces ( { } ) at the either ends and have key-value
pairs inside the braces. Each key-value pair inside braces are separated by comma
(, ). JSON object looks something like this :
Conversion of JSON text to Javascript Object
JSON text/object can be converted into Javascript object using the function JSON.parse().
For getting the value of any key from a Javascript object, we can use the values as: object1.rollno
If we pass a invalid JSON text to the function JSON.parse(), it will generate error (no output is displayed
when using in tag of HTML).
Examples : Here, in example, the JSON text ‘jsonobj’ have 3 key-value pair. Each of the
pairs were able to be accessed by the Javascript object ‘obj’ using dot ( . ). ‘obj’ was a
javascript object which was the result of the function JSON.parse().
Converting JSON to JavaScript Objects
A JSON string represents a JavaScript object in string form. The string syntax is very similar to code, so it’s easy to
understand. You can use the JSON.parse(string) method to convert a string that is properly formatted with JSON into a
JavaScript object.
For example, in the following code snippet, notice that accountStr is defined as a formatted JSON string, then converted to a
JavaScript object using JSON.parse() and then member properties can be accessed via dot notation:
Example program to convert JSON into Javascript object:
<html>
<body>
<h2>Converting JSON Text into Javascript Object</h2>
<b>JSON Object :</b>
<p id="demo"></p>
<b>Use of Javascript object :</b>
<p id="demo1"></p>
<script>
var jsonobj ='{ "name":"Brendan Eich","designerof":"Javascript","bornin":"1961" }';
// Here we convert JSON to object
var obj = JSON.parse(jsonobj);
document.getElementById("demo1").innerHTML =
obj.name + ", who was born in "
+ obj.bornin + ", was the designer of "
+ obj.designerof;
document.getElementById("demo").innerHTML =jsonobj;
</script>
</body>
</html>
Conversion of JSON object to string example: using stringify method