File SystemΒΆ
NodeJS comes with an extensive file system API in a module called fs
.
However, the module is traditionally based on callbacks. In this book,
we will be focused on writing codes using promise based APIs which can
be easily used in async/await
paradigm. Hence, we will use
a library named fs-extra.
Checking existence of a file
1 2 3 4 5 6 7 8 9 10 11 | const fs = require('fs-extra');
(async () => {
let filename = './fs.rst';
let exists = await fs.pathExists(filename);
if (exists){
console.log(`The file ${filename} exists.`);
} else {
console.log(`The file ${filename} does not exist.`);
}
})();
|
Reading a file
1 2 3 4 5 6 7 8 9 | const fs = require('fs-extra');
(async () => {
// The readFile function reads the contents of a file in a buffer.
let contents = await fs.readFile('read_file.js');
// Buffer can be converted into string for further processing.
let contents_str = contents.toString();
console.log(contents_str);
})();
|