The FS Module for File operations

Node File API is much similar to UNIX POSIX. File descriptors are integers representing the index of an entry on the process file descriptor table.
There are 3 special file descriptors -
1 - Standard input
2 - Standard output
3 - Standard error

Node has a module called path that provides various convinience functions for dealing with file paths. These functions do not touch the actual file system, they only work on strings.
 
Path Module
1) path.normalize - takes care of ., .., // and converts all strings to normal form. Must be used when paths are entered by users.
2) path.join - used to concantenate paths. You can pass as many arguments as you like. It also normalizes the path
3) path.resolve - can convert a series of paths into a normalized absolute path. You can pass any number of arguments, it will work as if running a cd command on all arguments one by one. If the final path is not absolute, it will prepend the CWD to it to make it absolute
4) path.relative - it takes in 2 absolute paths and then gives a relative path that can take you from path1 to path2.
5) path.dirname - gets the directory of the file path passed as an argument
6) path.basename - gets the file name from the path passed as an argument
7) path.extname - gets the file extension (along with .) of the path passed as argument
8) path.exists - determine whether a path exists or not
 
FS Module
The FS module is where all the file manipulation and query functions are stored.
All the functions are available in synchronous as well as asynchronous form. The async form functions generally return their result to a callback with 2 parameters - the first one being an error variable (which is set if an error occured). The sync functions return value to the caller. Their name is suffixed with -Sync.

1) fs.stat (file_name, callback(information)) - returns the information about the file/directory
2) fs.open (file_name, access_level, callback(error, descriptor)) - opens the file and returns the file descriptor
3) fs.read (file_descriptor, output_buffer, buffer_offset, bytes_to_read, start_position, callback(err, no_of_bytes_read))
4) fs.write(file_descriptor, buffer_to_write, buffer_offset, bytes_to_write, file_offset, callback(err, bytes_written))
5) fs.close(file_descriptor) - close the opened file

No comments:

Post a Comment