Like Http, IO is non-blocking, It is also very commonly used, not as often as Http, but still good to know its funtionality.
readFile/readFileSync
fs.readFile(filename, [encoding], [callback])
The callback is passed two arguments (err, data), where data is the contents of the file.
fs.readFileSync(filename, [encoding])
return the content of the file, no callback needed.
Both of them reads a file, readFileSync read at once and readFile use asynchronous reading, so it has callback functions.
var fs = require('fs');
var filehandle = fs.readFile('data.txt', function(err, data) {
if(err)throw err;
console.log(data);
});
output
By default, readFile reads Buffer, to read in utf-8 format:
fs.readFile( 'data.txt', 'utf-8', function(err, data) {...}
fs.stat(path, [callback])
fs.statSync(path)
return a
fs.Stats object that contains the information about the file
fs.Stats contains the methods and data about the file like last modified, size etc
fs.createReadStream(path, [options])
return a new Readable Stream object, Readable Stream and Writable Stream are inside the Stream module
Readable Stream object have the following events and methods
data - emits a Buffer or string( if encoding is set )
end - receive EOF
error
close - resource is closed
methods - pause(), resume(),
pipe(destination, [options]) - pipes a readable stream to a writable stream
Buffer
creating buffer
new Buffer( 10 )
- create a buffer of size 10, uninitialized, this is the most common way of creating buffer
buffer class have many methods to read and write to a buffer
property: length
method: [] operator - to get the bite in the index
write - write the string to the buffer