Using Node.js File System Module
Node.js File System Module helps you to work with files on your computer or server.You can read, edit, write, create or rename files.
To use file system you need to import them i.e var fs=require(‘fs’)
To read files on your computer we use function fs.readFile() function.
Let say you have below HTML file saved as “demo.html” in the same folder as your node.js
We can create a node.js code to read the file and display it in a web browser.
Save below code as file_demo.xml
Creating Files and adding content to them
Node.js File module has below functions for creating and adding content to files.
- fs.appendFile()-this function creates a file and adds content to it.If the specified file exists, the content is just added to it.Example code.
- fs.open()-this function takes a ‘flag’ w which means it opens the file for writing.If the file specified does not exists it created and it it exists its opened for writing.
- fs.writeFile()-this function creates a file and adds the content,if the file exists,its replaced with it content.
You can use fs.writeFile() and fs.appendFile() function to update files with new content.
How to delete files
fs.unlink() function is used to delete files.
If the file does not exist the function will throw an error.
How to rename existing files
We can rename existing files using fs.rename() function