This is the second installment of the 5 part set of Useful file operations in nodejs. Please check its
part-1 before proceeding any further. It is recommended but the content is not inter-related so do as it suits your requirements.
It is used to append data at the end of a currently existing file Asynchronously or It will create the file if the file does not exist.
// you have to pass the Relative path of the file from the Current working directory.
//The content to be appended is stored in variable "new_content" and it will be passed to the function.
new_content = "This data will be appended at the end of the file.";
fs.appendFile('data.txt', new_content , (err) => {
if(err)
throw err;
console.log('The new_content was appended successfully');
});
// To check it's Asynchronous nature !
console.log("This method is Asynchronous");
It is used to append data at the end of a currently existing file Synchronously or It will create the file if the file does not exist.
// you have to pass the Relative path of the file from the Current working directory.
//The content to be appended is stored in variable "new_content" and it will be passed to the function.
new_content = "This data will be appended at the end of the file.";
fs.appendFileSync('data.txt', new_content);
console.log('The new_content was appended successfully');
// To check it's Synchronous nature !
console.log("This method is Synchronous");
It is used to rename an already existing file Asynchronously.
// you have to pass the Relative path of the file from the Current working directory.
fs.rename('data.txt', 'new_data.txt', (err) => {
if (err)
throw err;
console.log('File renamed successfully');
});
// To check it's Asynchronous nature !
console.log("This method is Asynchronous");
It is used to rename an already existing file Synchronously.
// you have to pass the Relative path of the file from the Current working directory.
fs.renameSync('data.txt', 'new_data.txt');
console.log('File renamed successfully');
// To check it's Synchronous nature !
console.log("This method is Synchronous");