In this chapter , we will discuss the following topics related to File Handling
To delete a file with the File System module, you will use fs.unlink() method.The fs.unlink() method deletes file.
Example
var fs = require("fs");
fs.unlink('C:\myTest.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
Output :
'File deleted!'
Rename File
To rename file with the File System module, you will use fs.rename() method.The fs.rename() method rename file.
Example
var fs = require("fs");
fs.rename('myFile.txt', 'myFile2.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
})
Output :
'File Renamed!'
Truncate File
To rename file with the File System module, you will use fs.ftruncate() method.The fs.ftruncate() method rename file.
Example
var fs = require('fs')
fs.truncate('input.txt', 0, function()
{
console.log('File Truncated')
})
Output :
'File Truncated!'
Copy File
To Copy file with the File System module, you will use fs.copyFile() method.The fs.copyFile() method Copy file.
Example
var fs = require('fs');
fs.copyFile('input.txt', 'DestinationFile.txt', (err) => {
if (err) throw err;
console.log('input.txt was copied to DestinationFile.txt');
});
Output :
'input.txt was copied to DestinationFile.tx'
https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback
- Delete File
- Rename File
- Truncate File
- Copy File
To delete a file with the File System module, you will use fs.unlink() method.The fs.unlink() method deletes file.
Example
var fs = require("fs");
fs.unlink('C:\myTest.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
Output :
'File deleted!'
Rename File
To rename file with the File System module, you will use fs.rename() method.The fs.rename() method rename file.
Example
var fs = require("fs");
fs.rename('myFile.txt', 'myFile2.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
})
Output :
'File Renamed!'
Truncate File
To rename file with the File System module, you will use fs.ftruncate() method.The fs.ftruncate() method rename file.
Example
var fs = require('fs')
fs.truncate('input.txt', 0, function()
{
console.log('File Truncated')
})
Output :
'File Truncated!'
Copy File
To Copy file with the File System module, you will use fs.copyFile() method.The fs.copyFile() method Copy file.
Example
var fs = require('fs');
fs.copyFile('input.txt', 'DestinationFile.txt', (err) => {
if (err) throw err;
console.log('input.txt was copied to DestinationFile.txt');
});
Output :
'input.txt was copied to DestinationFile.tx'
https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback