File system in node.js a module 'fs' which provide the utility/API to interact with files and its manipulation async / sync way.
All utilities takes callback argument and have first output parameter as err, to handle error first.
If there is not any error, it will be null/undefined.
How to import in application;
const fs = require('fs');
File system (fs) have a big list of API which we use according to the requirements in async/sync way.
A file system needs a path of the file which can be a string/buffer/url.
Some of the mostly used API we are discussing below:
fs.open(path[, flags[, mode]], callback):
- -It works asynchronously to open a file.
- -To work in sync way we have to use fs.openSync()
Example:
const fs = require('fs');
fs.open('/open/some/file.txt', 'r', (err, fd) => {
if (err) throw err;
fs.close(fd, (err) => {
if (err) throw err;
});
});
- fs.close(fd,callback) / fs.closeSync(fd) : To close the connection with file stream
- fs.readFile(path[, options], callback) / fs.readFileSync(path[, options]) : To read the file asyns/sync manner
- fs.mkdir(path[, options], callback) / fs.mkdirSync(path[, options]) : To new create directory at the specified path
- fs.rmdir(path, callback) / fs.rmdirSync(path) : To remove the specified directory async/sync
- fs.copyFile(src, dest[, flags], callback) / fs.copyFileSync(src, dest[, flags]) : To create copy of file from source to destination