NODE.
JS - FILE SYSTEM
[Link] Copyright © [Link]
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 [Link] having following content
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Let us create a js file named [Link] having the following code.
var fs = require("fs");
// Asynchronous read
[Link]('[Link]', function (err, data) {
if (err) {
return [Link](err);
}
[Link]("Asynchronous read: " + [Link]());
});
// Synchronous read
var data = [Link]('[Link]');
[Link]("Synchronous read: " + [Link]());
[Link]("Program Ended");
Now run the [Link] to see the result:
$ node [Link]
Verify the Output
Synchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
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:
[Link](path, flags[, mode], callback)
Parameters
Here is the description of the parameters used:
path - This is string having file name including path.
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 in synchronous mode.
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.
wx Like 'w' but fails if path exists.
w+ Open file for reading and writing. The file is created ifitdoesnotexist or truncated ifitexists.
wx+ Like 'w+' but fails if path exists.
a Open file for appending. The file is created if it does not exist.
ax Like 'a' but fails if path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like 'a+' but fails if path exists.
Example
Let us create a js file named [Link] having the following code to open a file [Link] for reading
and writing.
var fs = require("fs");
// Asynchronous - Opening File
[Link]("Going to open file!");
[Link]('[Link]', 'r+', function(err, fd) {
if (err) {
return [Link](err);
}
[Link]("File opened successfully!");
});
Now run the [Link] to see the result:
$ node [Link]
Verify the Output
Going to open file!
File opened successfully!
Get File information
Syntax
Following is the syntax of the method to get the information about a file:
[Link](path, callback)
Parameters
Here is the description of the parameters used:
path - This is string having file name including path.
callback - This is the callback function which gets two arguments err, stats where stats is an
object of [Link] 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 [Link] class which can be used to check file type. These methods
are given in the following table.
Method Description
[Link] Returns true if file type of a simple file.
[Link] Returns true if file type of a directory.
[Link] Returns true if file type of a block device.
[Link] Returns true if file type of a character device.
[Link] Returns true if file type of a symbolic link.
[Link] Returns true if file type of a FIFO.
[Link] Returns true if file type of asocket.
Example
Let us create a js file named [Link] having the following code:
var fs = require("fs");
[Link]("Going to get file info!");
[Link]('[Link]', function (err, stats) {
if (err) {
return [Link](err);
}
[Link](stats);
[Link]("Got file info successfully!");
// Check file type
[Link]("isFile ? " + [Link]());
[Link]("isDirectory ? " + [Link]());
});
Now run the [Link] to see the result:
$ node [Link]
Verify the Output
Going to get file info!
{ dev: 1792,
mode: 33188,
nlink: 1,
uid: 48,
gid: 48,
rdev: 0,
blksize: 4096,
ino: 4318127,
size: 97,
blocks: 8,
atime: Sun Mar 22 2015 [Link] GMT-0500 (CDT),
mtime: Sun Mar 22 2015 [Link] GMT-0500 (CDT),
ctime: Sun Mar 22 2015 [Link] GMT-0500 (CDT) }
Got file info successfully!
isFile ? true
isDirectory ? false
Writing File
Syntax
Following is the syntax of one of the methods to write into a file:
[Link](filename, data[, options], callback)
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:
path - This is string having file name including path.
data - This is the String or Buffer to be written into the file.
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 [Link] having the following code:
var fs = require("fs");
[Link]("Going to write into existing file");
[Link]('[Link]', 'Simply Easy Learning!', function(err) {
if (err) {
return [Link](err);
}
[Link]("Data written successfully!");
[Link]("Let's read newly written data");
[Link]('[Link]', function (err, data) {
if (err) {
return [Link](err);
}
[Link]("Asynchronous read: " + [Link]());
});
});
Now run the [Link] to see the result:
$ node [Link]
Verify the Output
Going to write into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Simply Easy Learning!
Reading File
Syntax
Following is the syntax of one of the methods to read from a file:
[Link](fd, buffer, offset, length, position, callback)
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:
fd - This is the file descriptor returned by file [Link] method.
buffer - This is the buffer that the data will be written to.
offset - This is the offset in the buffer to start writing at.
length - This is an integer specifying the number of bytes to read.
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 [Link] having the following code:
var fs = require("fs");
var buf = new Buffer(1024);
[Link]("Going to open an existing file");
[Link]('[Link]', 'r+', function(err, fd) {
if (err) {
return [Link](err);
}
[Link]("File opened successfully!");
[Link]("Going to read the file");
[Link](fd, buf, 0, [Link], 0, function(err, bytes){
if (err){
[Link](err);
}
[Link](bytes + " bytes read");
// Print only read bytes to avoid junk.
if(bytes > 0){
[Link]([Link](0, bytes).toString());
}
});
});
Now run the [Link] to see the result:
$ node [Link]
Verify the Output
Going to open an existing file
File opened successfully!
Going to read the file
97 bytes read
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Closing File
Syntax
Following is the syntax of one of the methods to close an opened file:
[Link](fd, callback)
Parameters
Here is the description of the parameters used:
fd - This is the file descriptor returned by file [Link] method.
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 [Link] having the following code:
var fs = require("fs");
var buf = new Buffer(1024);
[Link]("Going to open an existing file");
[Link]('[Link]', 'r+', function(err, fd) {
if (err) {
return [Link](err);
}
[Link]("File opened successfully!");
[Link]("Going to read the file");
[Link](fd, buf, 0, [Link], 0, function(err, bytes){
if (err){
[Link](err);
}
// Print only read bytes to avoid junk.
if(bytes > 0){
[Link]([Link](0, bytes).toString());
}
// Close the opened file.
[Link](fd, function(err){
if (err){
[Link](err);
}
[Link]("File closed successfully.");
});
});
});
Now run the [Link] to see the result:
$ node [Link]
Verify the Output
Going to open an existing file
File opened successfully!
Going to read the file
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
File closed successfully.
Truncate File
Syntax
Following is the syntax of the method to truncate an opened file:
[Link](fd, len, callback)
Parameters
Here is the description of the parameters used:
fd - This is the file descriptor returned by file [Link] method.
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 [Link] having the following code:
var fs = require("fs");
var buf = new Buffer(1024);
[Link]("Going to open an existing file");
[Link]('[Link]', 'r+', function(err, fd) {
if (err) {
return [Link](err);
}
[Link]("File opened successfully!");
[Link]("Going to truncate the file after 10 bytes");
// Truncate the opened file.
[Link](fd, 10, function(err){
if (err){
[Link](err);
}
[Link]("File truncated successfully.");
[Link]("Going to read the same file");
[Link](fd, buf, 0, [Link], 0, function(err, bytes){
if (err){
[Link](err);
}
// Print only read bytes to avoid junk.
if(bytes > 0){
[Link]([Link](0, bytes).toString());
}
// Close the opened file.
[Link](fd, function(err){
if (err){
[Link](err);
}
[Link]("File closed successfully.");
});
});
});
});
Now run the [Link] to see the result:
$ node [Link]
Verify the Output
Going to open an existing file
File opened successfully!
Going to truncate the file after 10 bytes
File truncated successfully.
Going to read the same file
Tutorials
File closed successfully.
Delete File
Syntax
Following is the syntax of the method to delete a file:
[Link](path, callback)
Parameters
Here is the description of the parameters used:
path - This is the file name including path.
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 [Link] having the following code:
var fs = require("fs");
[Link]("Going to delete an existing file");
[Link]('[Link]', function(err) {
if (err) {
return [Link](err);
}
[Link]("File deleted successfully!");
});
Now run the [Link] to see the result:
$ node [Link]
Verify the Output
Going to delete an existing file
File deleted successfully!
Create Directory
Syntax
Following is the syntax of the method to create a directory:
[Link](path[, mode], callback)
Parameters
Here is the description of the parameters used:
path - This is the directory name including path.
mode - This is the directory permission to be set. Defaults to 0777.
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 [Link] having the following code:
var fs = require("fs");
[Link]("Going to create directory /tmp/test");
[Link]('/tmp/test',function(err){
if (err) {
return [Link](err);
}
[Link]("Directory created successfully!");
});
Now run the [Link] to see the result:
$ node [Link]
Verify the Output
Going to create directory /tmp/test
Directory created successfully!
Read Directory
Syntax
Following is the syntax of the method to read a directory:
[Link](path, callback)
Parameters
Here is the description of the parameters used:
path - This is the directory name including path.
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 [Link] having the following code:
var fs = require("fs");
[Link]("Going to read directory /tmp");
[Link]("/tmp/",function(err, files){
if (err) {
return [Link](err);
}
[Link]( function (file){
[Link]( file );
});
});
Now run the [Link] to see the result:
$ node [Link]
Verify the Output
Going to read directory /tmp
[Link]
[Link]
[Link]
hsperfdata_apache
test
[Link]
Remove Directory
Syntax
Following is the syntax of the method to remove a directory:
[Link](path, callback)
Parameters
Here is the description of the parameters used:
path - This is the directory name including path.
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 [Link] having the following code:
var fs = require("fs");
[Link]("Going to delete directory /tmp/test");
[Link]("/tmp/test",function(err){
if (err) {
return [Link](err);
}
[Link]("Going to read directory /tmp");
[Link]("/tmp/",function(err, files){
if (err) {
return [Link](err);
}
[Link]( function (file){
[Link]( file );
});
});
});
Now run the [Link] to see the result:
$ node [Link]
Verify the Output
Going to read directory /tmp
[Link]
[Link]
[Link]
hsperfdata_apache
[Link]
Methods Reference
Following is a reference of File System module available in [Link]. For a further detail you can
refer to official documentation.
SN Method & Description
1 [Link], newPath, callback
Asynchronous rename. No arguments other than a possible exception are given to the
completion callback.
2 [Link], len, callback
Asynchronous ftruncate. No arguments other than a possible exception are given to the
completion callback.
3 [Link], len
Synchronous ftruncate
4 [Link], len, callback
Asynchronous truncate. No arguments other than a possible exception are given to the
completion callback.
5 [Link], len
Synchronous truncate
6 [Link], uid, gid, callback
Asynchronous chown. No arguments other than a possible exception are given to the
completion callback.
7 [Link], uid, gid
Synchronous chown
8 [Link], uid, gid, callback
Asynchronous fchown. No arguments other than a possible exception are given to the
completion callback.
9 [Link], uid, gid
Synchronous fchown
10 [Link], uid, gid, callback
Asynchronous lchown. No arguments other than a possible exception are given to the
completion callback.
11 [Link], uid, gid
Synchronous lchown
12 [Link], mode, callback
Asynchronous chmod. No arguments other than a possible exception are given to the
completion callback.
13 [Link], mode
Synchronous chmod.
14 [Link], mode, callback
Asynchronous fchmod. No arguments other than a possible exception are given to the
completion callback.
15 [Link], mode
Synchronous fchmod.
16 [Link], mode, callback
Asynchronous lchmod. No arguments other than a possible exception are given to the
completion [Link] available on Mac OS X.
17 [Link], mode
Synchronous lchmod.
18 [Link], callback
Asynchronous stat. The callback gets two arguments err, stats where stats is a [Link]
object.
19 [Link], callback
Asynchronous lstat. The callback gets two arguments err, stats where stats is a [Link]
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 [Link], callback
Asynchronous fstat. The callback gets two arguments err, stats where stats is a [Link]
object. fstat is identical to stat, except that the file to be stat-ed is specified by the file
descriptor fd.
21 [Link]
Synchronous stat. Returns an instance of [Link].
22 [Link]
Synchronous lstat. Returns an instance of [Link].
23 [Link]
Synchronous fstat. Returns an instance of [Link].
24 [Link], dstpath, callback
Asynchronous link. No arguments other than a possible exception are given to the
completion callback.
25 [Link], dstpath
Synchronous link.
26 [Link], dstpath[, type], callback
Asynchronous symlink. No arguments other than a possible exception are given to the
completion callback. The type argument can be set to 'dir', 'file', or 'junction' defaultis ′ file ′
and is only available on Windows ignoredonotherplatforms. Note that Windows junction points
require the destination path to be absolute. When using 'junction', the destination
argument will automatically be normalized to absolute path.
27 [Link], dstpath[, type]
Synchronous symlink.
28 [Link], callback
Asynchronous readlink. The callback gets two arguments err, linkString.
29 [Link][, cache], callback
Asynchronous realpath. The callback gets two arguments err, resolvedPath. May use
[Link] to resolve relative paths. cache is an object literal of mapped paths that can
be used to force a specific path resolution or avoid additional [Link] calls for known real
paths.
30 [Link][, cache]
Synchronous realpath. Returns the resolved path.
31 [Link], callback
Asynchronous unlink. No arguments other than a possible exception are given to the
completion callback.
32 [Link]
Synchronous unlink.
33 [Link], callback
Asynchronous rmdir. No arguments other than a possible exception are given to the
completion callback.
34 [Link]
Synchronous rmdir.
35 [Link][, mode], callback
SAsynchronous mkdir2. No arguments other than a possible exception are given to the
completion callback. mode defaults to 0777.
36 [Link][, mode]
Synchronous mkdir.
37 [Link], 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 [Link]
Synchronous readdir. Returns an array of filenames excluding '.' and '..'.
39 [Link], callback
Asynchronous close. No arguments other than a possible exception are given to the
completion callback.
40 [Link]
Synchronous close.
41 [Link], flags[, mode], callback
Asynchronous file open.
42 [Link], flags[, mode]
Synchronous version of [Link].
43 [Link], atime, mtime, callback
44 [Link], atime, mtime
Change file timestamps of the file referenced by the supplied path.
45 [Link], atime, mtime, callback
46 [Link], atime, mtime
Change the file timestamps of a file referenced by the supplied file descriptor.
47 [Link], callback
Asynchronous fsync. No arguments other than a possible exception are given to the
completion callback.
48 [Link]
Synchronous fsync.
49 [Link], buffer, offset, length[, position], callback
Write buffer to the file specified by fd.
50 [Link], data[, position[, encoding]], callback
Write data to the file specified by fd. If data is not a Buffer instance then the value will be
coerced to a string.
51 [Link], buffer, offset, length[, position]
Synchronous versions of [Link]. Returns the number of bytes written.
52 [Link], data[, position[, encoding]]
Synchronous versions of [Link]. Returns the number of bytes written.
53 [Link], buffer, offset, length, position, callback
Read data from the file specified by fd.
54 [Link], buffer, offset, length, position
Synchronous version of [Link]. Returns the number of bytesRead.
55 [Link][, options], callback
Asynchronously reads the entire contents of a file.
56 [Link][, options]
Synchronous version of [Link]. Returns the contents of the filename.
57 [Link], data[, options], callback
Asynchronously writes data to a file, replacing the file if it already exists. data can be a
string or a buffer.
58 [Link], data[, options]
The synchronous version of [Link].
59 [Link], data[, options], callback
Asynchronously append data to a file, creating the file if it not yet exists. data can be a
string or a buffer.
60 [Link], data[, options]
The synchronous version of [Link].
61 [Link][, options], listener
Watch for changes on filename. The callback listener will be called each time the file is
accessed.
62 [Link][, 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.
63 [Link][, options][, listener]
Watch for changes on filename, where filename is either a file or a directory. The returned
object is a [Link].
64 [Link], 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 [Link]
Synchronous version of [Link].
66 [Link][, mode], callback
Tests a user's permissions for the file specified by path. mode is an optional integer that
specifies the accessibility checks to be performed.
67 [Link][, mode]
Synchronous version of [Link]. This throws if any accessibility checks fail, and does
nothing otherwise.
68 [Link][, options]
Returns a new ReadStream object.
69 [Link][, options]
Returns a new WriteStream object.
70 [Link], dstpath[, type], callback
Asynchronous symlink. No arguments other than a possible exception are given to the
completion callback. The type argument can be set to 'dir', 'file', or 'junction' defaultis ′ file ′
and is only available on Windows ignoredonotherplatforms. Note that Windows junction points
require the destination path to be absolute. When using 'junction', the destination
argument will automatically be normalized to absolute path.
Processing math: 100%