Geek Culture
Published in

Geek Culture

Using Node.JS File System

Hello, how are you all, friends, this time we will discuss the file system on Node.JS.

When we develop applications, we will always be dealing with the file system. File system, serves to access files on the computer. When we run JavaScript code in a browser, we really want to limit JavaScript in accessing the file system. This technique is called sandboxing. Sendboxing will protect our program from malicious programs, as well as theft that can rob users of their privacy.

You can learn more tutorials here:

Date Method in Javascript

Javascript Error Handling

Javascript Tutorial: Convert time am pm to 24 Hours

Node.js provides fs core modules that can make it easier for us to access the file system. Each method in the fs module is available in two versions, namely the asynchronous version (default) and the synchronous version.

To access files on the computer we can use the fs.readFile() method. This method accepts three arguments, namely: file location, encoding, and a callback function that will be called when the file is successfully/failed to access.

Reading Files in Nodejs

In Nodejs, there is a file system (fs) module that allows us to access the file system.

The file system module is often used for: 1

  • Read files;
  • Write files;
  • Rename files;
  • delete files;
  • etc.

This module is already in Nodejs, so we don’t need to install it via NPM (Node Package Manager).

Let’s try reading the file with the fs module. First please create an HTML file with the name index.html and fill it as follows:

I will give some examples.

Access the .txt file using the file system.

index.js

const fs = require('fs');

const fileReadCallback = (error, data) => {
if(error) {
console.log('Gagal membaca berkas');
return;
}
console.log(data);
};

todo.txt

My Header
My paragraph.

and you can also use the synchronous version of fs.readFileSync().

Basically, the code for using fs is the same. only way that can distinguish how to access the file system.

I will give an example of how to access the file system using html.

index.js

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('todo.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);

todo.html

<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>

Feel free to run using the command node index.js

Creating Nodejs Files

In addition to reading files, the fs module is also used to create new files. There are several methods that can be used to create files: 1

fs.appendFile() to create and populate a file;
fs.open() to create, open, and write files;
fs.writeFile() to create and write files.
Let’s try one by one.

First please create a javascript file with the name fs_append.js with the following contents:

var fs = require('fs');

//create a file named mynewfile1.txt:
fs.appendFile('mynewfile1.txt', 'Hello Teman Ngoding!', function (err) {
if (err) throw err;
console.log('Saved!');
});

Creating a file with the fs.open() function

The program code above will create a file with the name mynewfile1.txt with the contents Hello Friends Ngoding!.

Create a new javascript file with the name fs_open.js with the following contents:

var fs = require('fs');

fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});

The fs.open() function has three parameters:

  1. filename;
  2. Flags;
  3. The function to be executed when the file is opened.

In the example above, we set the w (write) flag to tell the fs.open() function if we want to write or create a new file.

Then the fs.open() function will create an empty file if there is no file with the specified name.

However, if the file already exists, the fs.open() function will override it.

Then when we want to read only the file, then we can give the flag r (read).

In addition to r and w, here are some flags that can be assigned: 3

  • r open the file for reading. If the file does not exist, an error will occur.
  • r+ opens the file for reading and writing. If the file does not exist, an error will occur.
  • rs opens the file to be read in synchronous mode.
  • rs+ opens files for reading and writing in synchronous mode.
  • w open the file e for writing.
  • wx is the same as w, but will error if the file already exists.
  • w+ opens file for writing and reading.
  • wx+ is the same as w+ but will error if the file already exists.
  • a open the file for filling.
  • ax is the same as a but will error if the file already exists.
  • a+ open file for filling.
  • ax+ is the same as a+ but will error if the file already exists.

Rename Files with Nodejs

In the fs module there is a rename() function to change the name.

This function has three parameters:

  1. filename;
  2. New name;
  3. Function to be executed when name is changed.

Create a new javascript file with the name rename.js and fill it with the following code:

var fs = require('fs');

fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});

Deleting Files with Nodejs

The fs module has an unlink() function to delete files. This function has two parameters:

The name of the file to be deleted;
function to be executed when the file is deleted.
Create a new file called delete.js, then fill it with the following code:

var fs = require('fs');

fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});

Thus I convey this tutorial, I hope it is useful.

Thanks.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store