⬆️ ⬇️

Node.js for beginners: the basics of working with files

Today we will talk about how to work with the file system using Node.js, consider the basic operations performed with files. These operations include the following:





The need to perform such operations arises in a variety of situations.







Fs module



Node.js has a standard module, fs (short for File System), which gives the developer the means to work with the file system. You can import it into the project as follows:

')

 var fs = require('fs'); 


The methods of this module are presented in synchronous and asynchronous forms. Callback functions that are passed to asynchronous methods take an error object as the first parameter, and data returned from the successful execution of the operation as the second parameter. Consider an example:



 function fileHandler(){   fs.readFile('textFile.txt', 'utf8', (err, data) => {       if(err) throw err;       console.log(data);   }); } 


The .readFile() method, which we'll talk about .readFile() , is intended for reading files. In this example, the callback function has two parameters, err and data . The first parameter contains errors that may occur when trying to read a file, the second is the data obtained after the successful execution of the operation. Note that .readFile() is an asynchronous method of the fs module. Its synchronous version is called .readFileSync() . A similar approach is used to name other methods of the module.



Creating a new file



Let's start with an example:



 function fileHandler(){   fs.open('testFile.txt', 'w', (err) => {       if(err) throw err;       console.log('File created');   });  } 


Here, the fs.open() method is used to create a new file. It takes the file name as the first argument. Its second argument is a flag indicating to the system what exactly we want to do with the file. In this case, it is the w flag (short for writing), which indicates that we want to open the file for writing. The .open() method can accept various flags. Here are some of them:



  1. r : open file for reading
  2. r+ : open file for reading and writing
  3. rs : open file for reading in synchronous mode
  4. w : open file for writing
  5. a : open file to write data to the end of file
  6. a+ : open file for reading and writing data to the end of file


Now, before moving on to the next example, testFile.txt edit the newly created testFile.txt file with a text editor. Fill in the following text:



 This is a test file. We're learning about Node.js File System. The End. 


Write data to file



Let's talk about how to add something to the file:



 function fileHandler(){   fs.appendFile('testFile.txt', ' This line is beyond the end.', (err) => {       if(err) throw err;       console.log('Data has been added!');   }); } 


Here we use the .appendFile() method to add data to the end of an existing file. As the first argument, this method takes the name of the file, as the second - the data that needs to be added to the end of the file. The third argument is, as usual, the callback function.



After the code shown above has successfully completed, the contents of the file will look like this:



 This is a test file. We're learning about Node.js File System. The End. This line is beyond the end. 


There is another way to write data to a file. It involves the use of the .writeFile() method. This method is very similar to .appendFile() , but it has one important difference. The fact is that using the .appendFile() method, we add new data to the file after the data that it already has. And when using the .writeFile() method, the contents of the file are replaced with a new one. Test this method:



 function fileHandler(){   fs.writeFile('testFile.txt', "I'm the replacement you've been looking for.", (err) => {       if(err) throw err;       console.log('Data has been replaced!');   }); } 


After successful operation, the file will contain the following text:



 I'm the replacement you've been looking for. 


As you can see, the file contents are completely replaced by new ones.



Reading file



For reading files, the fs module provides the .readFile() method, an example of the use of which we have already seen. As the first parameter, it takes the name of the file, as the second - the encoding. The third parameter is the callback function. We will try to output the contents of the testFile.txt file to the console using this method:



 function fileHandler(){   fs.readFile('testFile.txt', 'utf8', (err, data) => {       if(err) throw err;       console.log('--------- [File Data] ---------');       console.log(data);       console.log('--------- [File Data] ---------');   }); } 


That's what we get.





File data displayed in the console



Now let's talk about renaming files.



Rename file



To rename files, use the .rename() method:



 function fileHandler(){   fs.rename('testFile.txt', 'newTestFile.txt', (err) => {       if(err) throw err;       console.log('File renamed successfully!');   }); } 


The first argument of the method is the name of an existing file, the second is the new name of this file. After successfully calling this method, the testFile.txt file testFile.txt converted to newTestFile.txt .



Delete file



To delete files, use the .unlink() method:



 function fileHandler(){   fs.unlink('newTestFile.txt', (err) => {       if(err) throw err;       console.log('File deleted successfully!');   }); } 


A successful call to this method deletes the file newTestFile.txt .



Results



In this article, we looked at the basics of working with the file system in the Node.js environment. If you want to learn more about this topic - take a look at this material from the Node.js publication series, read the documentation for the fs module and try to practice everything you learn.



Dear readers! Do you use a standard fs module or something else to work with files in Node.js?



Source: https://habr.com/ru/post/452566/



All Articles