nodejs_file_system
nodejs_file_system
JS - FILE SYSTEM
http://www.tutorialspoint.com/nodejs/nodejs_file_system.htm Copyright © tutorialspoint.com
Node implements File I/O using simple wrappers around standard POSIX functions. Node File
System fs module can be imported using following syntax:
var fs = require("fs")
Synchronous vs Asynchronous
Every method in fs module have synchronous as well as asynchronous form. Asynchronous
methods takes a last parameter as completion function callback and first parameter of the
callback function is error. It is preferred to use asynchronous method instead of synchronous
method as former never block the program execution where as the second one does.
Example
Create a text file named input.txt having following content
var fs = require("fs");
// Asynchronous read
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());
console.log("Program Ended");
$ node main.js
Program Ended
Asynchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Following section will give good examples on major File I/O methods.
Open a File
Syntax
Following is the syntax of the method to open a file in asynchronous mode:
fs.open(path, flags[, mode], callback)
Parameters
Here is the description of the parameters used:
flags - Flag tells the behavior of the file to be opened. All possible values have been
mentioned below.
mode - This sets the file mode permissionandstickybits, but only if the file was created. It defaults
to 0666, readable and writeable.
callback - This is the callback function which gets two arguments err, fd.
Flags
Flags for read/write operations are:
Flag Description
r Open file for reading. An exception occurs if the file does not exist.
r+ Open file for reading and writing. An exception occurs if the file does not exist.
rs+ Open file for reading and writing, telling the OS to open it synchronously. See notes for
'rs' about using this with caution.
w Open file for writing. The file is created ifitdoesnotexist or truncated ifitexists.
w+ Open file for reading and writing. The file is created ifitdoesnotexist or truncated ifitexists.
a Open file for appending. The file is created if it does not exist.
a+ Open file for reading and appending. The file is created if it does not exist.
Example
Let us create a js file named main.js having the following code to open a file input.txt for reading
and writing.
var fs = require("fs");
$ node main.js
Syntax
Following is the syntax of the method to get the information about a file:
fs.stat(path, callback)
Parameters
Here is the description of the parameters used:
callback - This is the callback function which gets two arguments err, stats where stats is an
object of fs.Stats type which is printed below in the example.
Apart from the important attributes which are printed below in the example, there are number of
useful methods available in fs.Stats class which can be used to check file type. These methods
are given in the following table.
Method Description
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
$ node main.js
Writing File
Syntax
Following is the syntax of one of the methods to write into a file:
This method will over-write the file if file already exists. If you want to write into an existing file then
you should use another method available.
Parameters
Here is the description of the parameters used:
options - The third parameter is an object which will hold {encoding, mode, flag}. By default
encoding is utf8, mode is octal value 0666 and flag is 'w'
callback - This is the callback function which gets a single parameter err and used to to
return error in case of any writing error.
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
$ node main.js
Reading File
Syntax
Following is the syntax of one of the methods to read from a file:
This method will use file descriptor to read the file, if you want to read file using file name directly
then you should use another method available.
Parameters
Here is the description of the parameters used:
buffer - This is the buffer that the data will be written to.
position - This is an integer specifying where to begin reading from in the file. If position is
null, data will be read from the current file position.
callback - This is the callback function which gets the three arguments, err, bytesRead, buffer.
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
var buf = new Buffer(1024);
$ node main.js
Closing File
Syntax
Following is the syntax of one of the methods to close an opened file:
fs.close(fd, callback)
Parameters
Here is the description of the parameters used:
callback - This is the callback function which gets no arguments other than a possible
exception are given to the completion callback.
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
var buf = new Buffer(1024);
$ node main.js
Truncate File
Syntax
Following is the syntax of the method to truncate an opened file:
Parameters
Here is the description of the parameters used:
len - This is the length of the file after which file will be truncated.
callback - This is the callback function which gets no arguments other than a possible
exception are given to the completion callback.
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
var buf = new Buffer(1024);
$ node main.js
Delete File
Syntax
Following is the syntax of the method to delete a file:
fs.unlink(path, callback)
Parameters
Here is the description of the parameters used:
callback - This is the callback function which gets no arguments other than a possible
exception are given to the completion callback.
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
$ node main.js
Create Directory
Syntax
Following is the syntax of the method to create a directory:
Parameters
Here is the description of the parameters used:
callback - This is the callback function which gets no arguments other than a possible
exception are given to the completion callback.
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
$ node main.js
Read Directory
Syntax
Following is the syntax of the method to read a directory:
fs.readdir(path, callback)
Parameters
Here is the description of the parameters used:
callback - This is the callback function which gets two arguments err, files where files is an
array of the names of the files in the directory excluding '.' and '..'.
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
$ node main.js
Remove Directory
Syntax
Following is the syntax of the method to remove a directory:
fs.rmdir(path, callback)
Parameters
Here is the description of the parameters used:
callback - This is the callback function which gets no arguments other than a possible
exception are given to the completion callback.
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
$ node main.js
Methods Reference
Following is a reference of File System module available in Node.js. For a further detail you can
refer to official documentation.
3 fs.ftruncateSyncfd, len
Synchronous ftruncate
5 fs.truncateSyncpath, len
Synchronous truncate
13 fs.chmodSyncpath, mode
Synchronous chmod.
15 fs.fchmodSyncfd, mode
Synchronous fchmod.
17 fs.lchmodSyncpath, mode
Synchronous lchmod.
18 fs.statpath, callback
Asynchronous stat. The callback gets two arguments err, stats where stats is a fs.Stats
object.
19 fs.lstatpath, callback
Asynchronous lstat. The callback gets two arguments err, stats where stats is a fs.Stats
object. lstat is identical to stat, except that if path is a symbolic link, then the link itself is
stat-ed, not the file that it refers to.
20 fs.fstatfd, callback
Asynchronous fstat. The callback gets two arguments err, stats where stats is a fs.Stats
object. fstat is identical to stat, except that the file to be stat-ed is specified by the file
descriptor fd.
21 fs.statSyncpath
Synchronous stat. Returns an instance of fs.Stats.
22 fs.lstatSyncpath
Synchronous lstat. Returns an instance of fs.Stats.
23 fs.fstatSyncfd
Synchronous fstat. Returns an instance of fs.Stats.
25 fs.linkSyncsrcpath, dstpath
Synchronous link.
28 fs.readlinkpath, callback
Asynchronous readlink. The callback gets two arguments err, linkString.
30 fs.realpathSyncpath[, cache]
Synchronous realpath. Returns the resolved path.
31 fs.unlinkpath, callback
Asynchronous unlink. No arguments other than a possible exception are given to the
completion callback.
32 fs.unlinkSyncpath
Synchronous unlink.
33 fs.rmdirpath, callback
Asynchronous rmdir. No arguments other than a possible exception are given to the
completion callback.
34 fs.rmdirSyncpath
Synchronous rmdir.
36 fs.mkdirSyncpath[, mode]
Synchronous mkdir.
37 fs.readdirpath, callback
Asynchronous readdir3. Reads the contents of a directory. The callback gets two
arguments err, files where files is an array of the names of the files in the directory
excluding '.' and '..'.
38 fs.readdirSyncpath
Synchronous readdir. Returns an array of filenames excluding '.' and '..'.
39 fs.closefd, callback
Asynchronous close. No arguments other than a possible exception are given to the
completion callback.
40 fs.closeSyncfd
Synchronous close.
47 fs.fsyncfd, callback
Asynchronous fsync. No arguments other than a possible exception are given to the
completion callback.
48 fs.fsyncSyncfd
Synchronous fsync.
56 fs.readFileSyncfilename[, options]
Synchronous version of fs.readFile. Returns the contents of the filename.
62 fs.unwatchFilefilename[, listener]
Stop watching for changes on filename. If listener is specified, only that particular listener
is removed. Otherwise, all listeners are removed and you have effectively stopped
watching filename.
64 fs.existspath, callback
Test whether or not the given path exists by checking with the file system. Then call the
callback argument with either true or false.
65 fs.existsSyncpath
Synchronous version of fs.exists.
67 fs.accessSyncpath[, mode]
Synchronous version of fs.access. This throws if any accessibility checks fail, and does
nothing otherwise.
68 fs.createReadStreampath[, options]
Returns a new ReadStream object.
69 fs.createWriteStreampath[, options]
Returns a new WriteStream object.