How to Create a New File with node.js


In this article, we show how to create a new file with node.js .

In this example, we create a simple text file (.txt file).

We can give this file any name that we want.

We also show how we can write contents to this text file, so that it isn't simply a blank text file.

So let's now go over the code that is needed to create a new file with node.js.

We create a text file that has the content inside, "This file was created with node.js".

So the code above is very short and simple.

In the first line, we must import the fs module. This is the module that is needed to create a new file. fs stands for file system. So we import the fs module using the require() function. We then create a constant, fs, that allows us to reference this imported module.

We then use the fs.writeFileSync() to create a new file.

The fs.writeFileSync() function takes in 2 parameters.

The first parameter is the name of the file, including the file extension, which decides the type of file it is. In thiscase, our file will be named "notes.txt".

The second parameter is the contents that you want to place in this file. If you put nothing, the file will be blank. However, you can put in contents. In this case, the contents, "This file was created with node.js", is placed in the file.

You then run the code and you should see that a new file is created named "notes.txt" in the directory that you are in.

And this is how to create a new file with node.js.

Related Resources

How to Find the Version of node.js Installed on Your Computer

HTML Comment Box is loading comments...