Node.js

How to create files with Node.js  (write files)

April 13, 2022

How to create files with Node.js  (write files)

In this article you will learn how to create files with Node.js – using the File System library, in a simple and intuitive way.

create files with Node thumb

What’s up programmers, ok? Let’s learn more about Node and how to handle files with this technology!

What is FileSystem? 

The File System is a local module of Node.js, whose main objective is to perform operations with files and directories

That is: create, update, delete, rename and any other operation you can think of

We can use it as follows:

const fs = require('fs');

As said before, it is a local module, the characteristic of local modules is that you can call them in any file from your project.

They all come installed with Node.js, so you don’t have to worry about setup

After the import, as shown above, you are ready to use the File System

In addition, as a feature of Node, the methods of the FS library have a synchronous and asynchronous version.

In a way that the synchronous version will wait for all processes to be executed to execute the next line of code, the asynchronous version has the promise of non-blocking

This is nothing more than going to the next code line, waiting for the answer of these asynchronous calls

Let’s see these approaches in the method that writes files with Node.js, the writeFile

Note: you can see the complete File System documentation here.

How to create files with Node – writeFile

To create files with Node we will use the File System library, as mentioned, but more specifically its writeFile method

To use writeFile, do this:

const data = 'Testing file creation...';

fs.writeFile('file.txt', data, (err) => {
 if (err) throw err;
 console.log('O arquivo foi criado!');
});

This way is asynchronous, notice that we insert a function in the method, which is called a callback

This function will only be executed when the creation of the .txt file is performed or an error occurs in this process

Note: The callback function is a feature of asynchronous calls!

Returning to the method: the first argument we see in writeFile is the name of the file that will be created

We can also insert the path, that is, the path where the file will be

And the second argument is the content of the file, which we insert in the data variable, just a simple text to serve as an example

But you can create any file extension and also with any data structure, a .json file with a JSON structure is perfectly valid

Finally, we will have the callback function that will only be executed at the end of the method

See that we have an argument called err, this argument contains the error that can be generated if something fails to create the file, and by the “if” inside the callback, it will be automatically executed if there is something in this argument

If not, everything proceeds normally and the success message via console.log is posted to the user.

It’s important to mention that the callback is written with an arrow function, a feature of the ES6 version of JavaScript to write functions, if you want to know more about it, check our other article here.

Be careful!

According to the documentation itself, it is not safe to use writeFile several times in the same file without waiting for the callback

There may be inconsistencies between what you want to save and what will be in the file

For this purpose, it is recommended to write to files in Stream, using the createWriteStream method.

And The Synchronous Version?

As said before, the writeFile method also exists in the synchronous version

For this method we will not have the callback function, because Node will execute the entire method to go to the next line of code

We can then say that the system will wait for the resolution of the writeFileSync method to proceed.

See its usage:

const data = 'testing sync';
fs.writeFileSync('file.txt', data);

In this way the position of the arguments is the same, first we type the target directory, with the name of the file to be created

And then the data that this file will have after its creation

Remembering that the action of creating files is commonly called writing files or writing to files (write file )

Which precisely constitutes the very name of the method, whether synchronous or asynchronous

Synchronous Or Asynchronous? Which One Should We Use?

The discussion is much longer than you might think, but there are some specific points that can help you choose which approach to use.

For example when dealing with very large files, either writing or reading

It is advised to use the asynchronous way so as not to block the application completely while the file is being read.

Use the same approach if you need to write large amounts of text to a file

How To Read The Contents Of A File

So far we’ve seen how to create files with Node or write whatever you want to call it 😀

But what if we need to read a file? Which method shall we use?

Once again we can use synchronous or asynchronous methods, and the method to handle this action is readFile

See it in action:

fs.readFile('file.txt', (err, data) => {
 if (err) throw err;
 console.log(data);
});

In readFile the situation is almost the same as in writeFile, we need to set the path of the file, that is, the pathway

And then we will get two arguments, the error and the file data

Again, we can print the errors if the program fails to read the file, but if it is successful, we can use the data as we wish.

Note that this method above is synchronous, so we have the presence of the callback with the arrow function, which will be executed at the end of the readFile process

The asynchronous version is even simpler:

const data = fs.readFileSync('file.txt');

In this way, it is necessary to assign the method to a variable, so that the data is inserted into it.

So we can handle this response from the readFileSync method however we want

And these are two possible ways to read files with Node

But once again the recommendation of Stream is valid, if the file is very large use this other approach to read the same

Conclusion

In this article we learned how to create files with Node or write files with Node, as mentioned before both terms are used

The writeFile method was presented, as well as its structure and use

This is the asynchronous way to write or create files with Node, to use the synchronous way the File System library method is writeFileSync

Each of the approaches has its uses, it is up to you to analyze what your software asks for each time you need to write a file

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x