Introduction: Why Learn to Work with Files in JavaScript?
\n\nWhen we talk about JavaScript, most people immediately think of the browser and interactive interfaces. However, with the advent of the Node.js platform, JavaScript has gone far beyond web pages. Today it is a full-fledged language for server-side development, automation, and utilities. And one of the key tasks every developer faces is working with the file system.
\n\nThe ability to read, write, move, and delete files is a fundamental skill without which no serious project can be imagined. Whether it's a logger, a configuration file, image uploads, or data analysis — access to the file system is needed everywhere.
\n\nIn this article, we will cover practical examples of working with the file system in Node.js. You will learn how to use the built-in fs module, what methods are available, and how to avoid common mistakes. All the code can be run and tested immediately.
Basic Methods of the fs Module
\n\nThe fs (File System) module is included in the standard Node.js distribution. It does not need to be installed separately. To get started, simply require it at the beginning of your file:
const fs = require('fs');\nconst fsPromises = require('fs').promises; // for working with promises\n\nAll methods of the fs module exist in three variants:
- \n
- Synchronous — block code execution until the operation completes. Usually have the
Syncsuffix. \n - Asynchronous with callbacks — the classic Node.js style. \n
- Asynchronous with promises — a modern approach using
fs.promises. \n
In modern projects, it is recommended to use promises and async/await. This makes the code cleaner and more understandable.
Reading Files
\n\nThe most common scenario is reading the contents of a file. Let's look at an example with a text file data.txt:
const fs = require('fs').promises;\n\nasync function readFileExample() {\n try {\n const data = await fs.readFile('data.txt', 'utf8');\n console.log('File contents:');\n console.log(data);\n } catch (err) {\n console.error('Error reading file:', err.message);\n }\n}\n\nreadFileExample();\n\nThe second parameter 'utf8' specifies the encoding. If you omit it, you will get a raw buffer. For text files, always specify the encoding.
Writing to a File
\n\nWriting data to a file can be done in two ways: complete overwrite or appending to the end.
\n\nOverwriting a file:
\nconst fs = require('fs').promises;\n\nasync function writeFileExample() {\n try {\n await fs.writeFile('output.txt', 'Hello, file system!');\n console.log('File successfully written');\n } catch (err) {\n console.error('Error writing:', err.message);\n }\n}\n\nwriteFileExample();\n\nAppending to the end of a file:
\nconst fs = require('fs').promises;\n\nasync function appendFileExample() {\n try {\n await fs.appendFile('log.txt', `New entry: ${new Date().toISOString()}\\n`);\n console.log('Data appended');\n } catch (err) {\n console.error('Error appending:', err.message);\n }\n}\n\nappendFileExample();\n\nThe appendFile method is ideal for logging or accumulating data.
Managing Directories and Files
\n\nWorking with the file system is not limited to reading and writing. Often you need to create folders, check if files exist, or delete them.
\n\nCreating and Deleting Directories
\n\nconst fs = require('fs').promises;\n\nasync function manageDirectories() {\n try {\n // Creating a directory (if it doesn't exist)\n await fs.mk