Node.js provides a built-in module called fs
(File System) that allows developers to work with the file system on their machine. This module provides both synchronous and asynchronous methods to read, write, update, delete, and rename files. Understanding how to use the fs
module is crucial for backend development tasks such as logging, data storage, and file manipulation.
The fs.readFile()
method is used to read files asynchronously. It doesn't block the execution of the program, making it ideal for non-blocking operations.
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
The fs.readFileSync()
method reads files synchronously, blocking the execution until the file is read. It's useful when you need to ensure that the file is read before proceeding.
const fs = require('fs');
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
The fs.writeFile()
method allows you to write data to a file asynchronously. It creates a new file if it doesn't exist, or overwrites the file if it does.
const fs = require('fs');
fs.writeFile('example.txt', 'Hello, World!', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File written successfully');
});
The fs.writeFileSync()
method writes data to a file synchronously. It's useful when you need to ensure that the data is written before proceeding.
const fs = require('fs');
try {
fs.writeFileSync('example.txt', 'Hello, Synchronous World!');
console.log('File written successfully');
} catch (err) {
console.error(err);
}
The fs.appendFile()
method is used to append data to a file asynchronously. If the file doesn't exist, it creates a new one.
const fs = require('fs');
fs.appendFile('example.txt', '\nAppended Text', (err) => {
if (err) {
console.error(err);
return;
}
console.log('Text appended successfully');
});
The fs.truncate()
method is used to truncate a file to a specified length. This can be useful for clearing or resizing a file.
const fs = require('fs');
fs.truncate('example.txt', 10, (err) => {
if (err) {
console.error(err);
return;
}
console.log('File truncated successfully');
});
The fs.unlink()
method is used to delete a file asynchronously. This is useful for cleaning up files that are no longer needed.
const fs = require('fs');
fs.unlink('example.txt', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File deleted successfully');
});
The fs.unlinkSync()
method deletes a file synchronously. This is useful when you need to ensure that the file is deleted before proceeding.
const fs = require('fs');
try {
fs.unlinkSync('example.txt');
console.log('File deleted successfully');
} catch (err) {
console.error(err);
}
The fs.rename()
method is used to rename a file asynchronously. This can also be used to move a file across directories.
const fs = require('fs');
fs.rename('oldname.txt', 'newname.txt', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File renamed successfully');
});
The fs.renameSync()
method renames a file synchronously. It's useful when you need to ensure that the file is renamed before proceeding.
const fs = require('fs');
try {
fs.renameSync('oldname.txt', 'newname.txt');
console.log('File renamed successfully');
} catch (err) {
console.error(err);
}
The fs.watch()
method allows you to monitor changes to a file or directory. It's useful for implementing features like auto-reloading or real-time updates.
const fs = require('fs');
fs.watch('example.txt', (eventType, filename) => {
console.log(`File ${filename} has been ${eventType}`);
});
The fs.chmod()
method is used to change the permissions of a file. This is important for securing files and controlling access.
const fs = require('fs');
fs.chmod('example.txt', 0o775, (err) => {
if (err) {
console.error(err);
return;
}
console.log('File permissions changed successfully');
});
File operations can often result in errors, such as when a file doesn't exist or there's a permission issue. Proper error handling is crucial to ensure your application runs smoothly and provides informative feedback.
const fs = require('fs');
fs.readFile('nonexistent.txt', 'utf8', (err, data) => {
if (err) {
console.error('An error occurred:', err.message);
return;
}
console.log(data);
});
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies