File Module
File Module
The Node.js file system module allows you to work with the file system on your
computer.
Read files
Create files
Update files
Delete files
Rename files
Read Files
Assume we have the following HTML file (located in the same folder as Node.js):
demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Create a Node.js file that reads the HTML file, and return the content:
Example Node.js Server inhtml.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Create Files
The File System module has methods for creating new files:
fs.appendFile()
fs.open()
fs.writeFile()
The fs.appendFile() method appends specified content to a file. If the file does
not exist, the file will be created:
1)appen1.js
var fs = require('fs');
fs.appendFile('abc.txt', 'Hello content!', function (err)
{
if (err) throw err;
console.log('Saved!');
});
The fs.open() 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:-openfile.js
Openfile.js
var fs = require('fs');
fs.open('writefile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});
The fs.writeFile() 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
Name:writefile.js
var fs = require('fs');
fs.appendFile()
fs.writeFile()
The fs.appendFile() method appends the specified content at the end of the specified
file:
Example
To delete a file with the File System module, use the fs.unlink() method.
Example
Delete "mynewfile2.txt":
var fs = require('fs');
Example
• var fs = require('fs');