Electron applications, being built with Node.js, have full access to the underlying operating system's file system. This is a powerful capability that allows your desktop apps to read, write, and manage files just like any other native application. Understanding how to interact with the file system is crucial for many common desktop application features, such as saving user preferences, opening and saving documents, managing project files, and more.
Node.js provides a built-in module called fs (File System) that exposes a comprehensive set of synchronous and asynchronous APIs for file operations. For Electron development, you'll primarily be using these fs module functions within your main process code, as it has direct access to the Node.js runtime.
The fs module offers two main styles of operation: synchronous and asynchronous. Synchronous operations block the Node.js event loop until the operation is complete, which can lead to unresponsive applications if not used carefully. Asynchronous operations, on the other hand, use callbacks or Promises, allowing other tasks to run while the file operation is in progress. For most user-facing operations in Electron, asynchronous methods are highly recommended to maintain a smooth user experience.
Let's explore some fundamental file system operations using the fs module.
To read the content of a file, you can use functions like fs.readFile() (asynchronous) or fs.readFileSync() (synchronous). The asynchronous version takes a file path, an optional options object (like encoding), and a callback function that receives an error object (if any) and the file data.
const fs = require('fs');
fs.readFile('my_document.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});For synchronous reading: