Node.js File System(fs) Module
Node.js File System Module is used for file handing which supports Read files, Create files, Update files, Delete files and Rename files.
We can include file system module as below in application
var fs = require('fs');
Read files
fs.readFile() method is used to read file.
Example :
const http = require('http');
const fs = require('fs');
const port = 5555;
const server = http.createServer(function (req, res) {
fs.readFile('aryatechno.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Welcome to aryatechno Node.js tutorials!');
});
}).listen(8080);
server.listen(port function() {
console.log(`Server running at port ${port}: http://127.0.0.1:${port}`)
})
Create files
Below Node.js module methods are used to create new files.
fs.open()
// Open file
fs.open('example.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
})
fs.writeFile()
//Writing to a File
fs.writeFile('example.txt', 'Hello, this is Node.js File System!', (err) => {
if (err) throw err;
console.log('File created and content written!');
});
Update Files
Below Node.js module methods are used to update contents into file.
fs.appendFile()
fs.writeFile()
fs.appendFile()
fs.appendFile('example.txt', '\nAppending this line!', (err) => {if (err) throw err;
console.log('Content appended successfully!');
});
Delete Files
Node.js module methods fs.unlink() is used to delete file.
//Deleting a File
fs.unlink('example.txt', (err) => {
if (err) throw err;
console.log('File deleted successfully!');
});
Rename Files
fs.rename() method is used to rename file.
//Renaming a File
fs.rename('example.txt', 'newfile.txt', (err) => {
if (err) throw err;
console.log('File renamed successfully!');
});
Creating a Folder/Directory
//Creating a Folder/Directory (fs.mkdir)
fs.mkdir('myFolder', (err) => {
if (err) throw err;
console.log('Folder created!');
});
Deleting a Folder
//Deleting a Folder (fs.rmdir)
fs.rmdir('myFolder', (err) => {
if (err) throw err;
console.log('Folder deleted!');
});
Checking If a File Exists (fs.existsSync)
if (fs.existsSync('example.txt')) {
console.log('File exists!');
} else {
console.log('File does not exist!');
}
Upload Files
formidable module is used to upload file.
Comments