Node.
js File System Module
[Link] as a File Server
The [Link] file system module allows you to work with the file system on your
computer.
To include the File System module, use the require() method:
var fs1 = require('fs');
Common use for the File System module:
Read files
Create files
Update files
Delete files
Rename files
Read Files
The [Link]() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as [Link]):
[Link]
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Create a [Link] file that reads the HTML file, and return the content:
Example [Link] Server [Link]
var http = require('http');
var fs = require('fs');
[Link](function (req, res) {
[Link]('[Link]', function(err, data) {
[Link](200, {'Content-Type': 'text/html'});
[Link](data);
return [Link]();
});
}).listen(8080);
Create Files
The File System module has methods for creating new files:
[Link]()
[Link]()
[Link]()
The [Link]() method appends specified content to a file. If the file does
not exist, the file will be created:
1)[Link]
var fs = require('fs');
[Link]('[Link]', 'Hello content!', function (err)
{
if (err) throw err;
[Link]('Saved!');
});
The [Link]() method takes a "flag" as the second argument, if the flag is "w" for
"writing", the specified file is opened for writing. If the file does not exist, an
empty file is created:
Example:-[Link]
Create a new, empty file using the open() method:
[Link]
var fs = require('fs');
[Link]('[Link]', 'w', function (err, file) {
if (err) throw err;
[Link]('Saved!');
});
The [Link]() method replaces the specified file and
content if it exists. If the file does not exist, a new file,
containing the specified content, will be created:
Example
Create a new file using the writeFile() method:
Name:[Link]
var fs = require('fs');
[Link]('[Link]', 'welcome!', function (err) {
if (err) throw err;
[Link]('Saved!');
});
Update Files
The File System module has methods for updating files:
[Link]()
[Link]()
The [Link]() method appends the specified content at the end of the specified
file:
Example
Append "This is my text." to the end of the file
Name:[Link]
var fs = require('fs');
[Link]('[Link]', ' I am Amruta.', function (err) {
if (err) throw err;
[Link]('Updated!');
});
Delete Files
To delete a file with the File System module, use the [Link]() method.
The [Link]() method deletes the specified file:
Example
Delete "[Link]":
var fs = require('fs');
[Link]('[Link]', function (err) {
if (err) throw err;
[Link]('File deleted!');
});
Rename Files
To rename a file with the File System module, use the [Link]() method.
The [Link]() method renames the specified file:
Example
• var fs = require('fs');
• [Link]('[Link]', '[Link]', function (err) {
• if (err) throw err;
• [Link]('File Renamed!');
• });