Node.js in Action : Create Simple Text File in Node.js Using "fs" Module

Welcome to the Node.js in Action article series. In this series we are seeing various real-time examples in node.js. In our previous articles we saw how to implement a simple HTTP server in node and to implement a countdown example. You can read them here.

In this example, we will learn to write/create a file using the "fs" module of node.js. As we know the "fs" module is used to manipulate files in the server. To create a file using the "fs" module, we need to call the writeFile() function of this module. The following is the documentation of the writeFile() function.

fs.writeFile(filename, data, [options], callback)

  1. Filename String
  2. Data String | Buffer
  3. Options Object

    • Encoding String | Null default = 'utf8'
    • Mode Number default = 438 (aka 0666 in Octal)
    • Flag String default = 'w'
       
  4. Callback Function

The writeFile() function asynchronously writes data to a file, replacing the file if it already exists. Data can be a string or a buffer.

The encoding option is ignored if the data is a buffer. It defaults to "utf8".

So, let's implement ith in an example. In this example we have omitted the optional third parameter.

var http = require('http');

var fs = require('fs');

var server = http.createServer(function (req, res) {

 

    fs.writeFile('message.txt', 'Just now, we have created this file', function (err) {

        if (err) throw err;

        console.log('It\'s saved! in same location.');

    });

 

});

server.listen(9090);

console.log('server running...')

As in the documentation, the first parameter is a filename and the second parameter is a string (we are passing in this example, rather than a buffer) and the third parameter is a callback function that will execute once the file writing is done.

After running the server from the console, we will see the message that the server is running.

Run the Server

Now, once we hit our HTTP server, we will see the successful message in the console window just as in the following.
 
message

If we check the server location we will find the “message.txt” file in the same location. No need to mention that we can save a message anywhere depending on requirements. Here is the output of this file, that is just created.
 
Output

Conclusion

In this example we have learned to create a simple text file using the "fs" module, I hope you have understood the simple example. In the next few articles we will see more interesting examples of node.js. Happy learning.

Up Next
    Ebook Download
    View all
    Learn
    View all