Blog for Learning

| lesson material | material summary | questions and answers | definitions | types and examples | other information | materi pelajaran | ringkasan materi | pertanyaan dan jawaban | definisi | jenis-jenis dan contoh-contoh | informasi lainnya |

Powered by Blogger.

Learning Nodejs # 5: How to Use the File System Module to Read Write Files

Nodejs Tutorial for Beginners: Use the Filesystem Module to read write files
In the previous tutorial, we have studied the HTTP module which is a module for creating web servers and doing HTTP Requests .
The following are examples of programs that have been created:
var http = require('http');
http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write('Hello <b>World</b>!');
    response.end();
}).listen(8000);

console.log("server running on http://localhost:8000");
In this code, we do hard coding of HTML code (write directly HTML code in nodejs code).
response.write('Hello <b>World</b>!');
What if there is an HTML file that we want to send in return?
To do this we need help from the module file system .
The process will be like this:
  1. Receive requests from users;
  2. Read HTML files on the server;
  3. Send a reply to the user.
In number two, we will use the file system module .
Okay, for more details ...
Let's start.

Read Files at Nodejs

In Nodejs, there is a file system ( fsmodule that allows us to access the file system .
File system modules are often used for: 1
  • Read file;
  • Write file;
  • Rename file;
  • delete file;
  • etc.
This module is already in Nodejs, so we don't need to install it via the NPM (Node Package Manager) . 2
To be able to use the module fswe must import it first with the function require().
var fs = require('fs');
Let's try reading the file with the module fsFirst, please create an HTML file with the name index.htmland contents as follows:
<!DOCTYPE html>
<html>
<head>
    <title>Tutorial Nodejs</title>
</head>
<body>
    <h1>Tutorial Nodejs Petanikode</h1>
    <p>Belajar Baca Tulis File di Nodejs</p>
</body>
</html>
Then create a new javacript code named baca_file.js with the contents as follows:
var fs = require('fs');
var http = require('http');

http.createServer(function (request, response) {

    // baca file
    fs.readFile('index.html', (err, data) => {
        if (err) throw err;
        
        // kirim respon
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
        response.end();
    });

}).listen(8000);

console.log("server running on http://localhost:8000");
Make sure the JavaScript and HTML files are in one folder.
HTML and Javascript files
After that, try executing baca_file.js:
node baca_file.js
Read Files at Nodejs
Yep! 🎉
We have successfully created a Nodejs server and sent an HTML file in return.
What should be noted in the code above is in this section:
// baca file
fs.readFile('index.html', (err, data) => {
    if (err) throw err;
       
    // kirim respon
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write(data);
    response.end();
});
Method readFile()is a method used to read files. Then this method has two parameters:
  1. File name;
  2. Functions that will be executed when the file is read.
In the code above, we use arrow function :
(err, data) => { ... }
The parameter errwill contain an error when the file fails to read and the parameter datawill contain data from the file.
Therefore, in this function we send a response to the client with parameters data.
// kirim respon
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
Then the response that will be received by the client will be in accordance with the contents of the file index.html.

Make a File on Nodejs

In addition to reading files, modules are fsalso used to create new files. There are several methods that can be used to create files: 1
  • fs.appendFile() to create and fill in files;
  • fs.open() to make, open, and write files;
  • fs.writeFile() to make and write files.
Let's try one by one.
First, please create a javascript file with the name fs_append.js as follows:
var fs = require('fs');

//create a file named mynewfile1.txt:
fs.appendFile('mynewfile1.txt', 'Hello dari Petanikode!', function (err) {
  if (err) throw err;
  console.log('Saved!');
});
The program code above will create a file with a name mynewfile1.txt with contents Hello dari petanikode!.
Let's try execution:
Make a file on nodejs
If we execute again node fs_append.js, then the contents of the file mynewfile1.txt will increase to:
Hello dari Petanikode!Hello dari Petanikode!
If we execute 10 times, the text Hello dari Petanikode! will be added 10 times.
This is the nature of the method fs.appendFile(), it will always add the contents of the file to each execution.

Make a file with the function fs.open ()

Then the next function / method is fs.open()This function has two functions, namely to open and write files.
Let's try ...
Make a new javascript file with the name fs_open.js as follows:
var fs = require('fs');

fs.open('mynewfile2.txt', 'w', function (err, file) {
  if (err) throw err;
  console.log('Saved!');
});
Then try executing:
Make a file with fs.open ()
The function fs.open()has three parameters:
  1. File name;
  2. Flag;
  3. The function that will be executed when the file is opened.
In the example above, we give Flag w (write) to tell the function fs.open()if we want to write or create a new file.
Then the function fs.open()will make the file empty if there is no file with the specified name.
However, if there is already a file, the function fs.open() will overwrite it.
Then when we want to read only the file, then we can give the flag r (read) .
Besides rand w, here are some flags that can be given: 3
  • ropen file to read. If the file does not exist, an error will occur.
  • r+open file to read and write. If the file does not exist, an error will occur.
  • rsopen file to read in synchronous mode .
  • rs+ open files to read and write in synchronous mode.
  • w open e-file for writing.
  • wxsame as w, but it will error if there is already a file.
  • w+ open the file to be written and read.
  • wx+same as w+but it will be an error if there is already a file.
  • a open file to fill.
  • axsame as abut it will be an error if there is already a file.
  • a+ open file to fill.
  • ax+same as a+but it will be an error if there is already a file.
To understand it, let's try creating a program to write and read files.
Means the flag that can be used is w+, because we will write first and then read it.
Make a file called Beru fs_open_wr.jswith the contents as follows:
var fs = require('fs');

fs.open('mynewfile2.txt', 'w+', function (err, file) {
    if (err) throw err;
    
    // kontent yang akan kita tulis ke file
    let content = "Hello Petanikode!";

    // tulis konten ke file
    fs.writeFile(file, content, (err) => {
        if (err) throw err;
        console.log('Saved!');
    }); 

    // baca file
    fs.readFile(file, (err, data) => {
        if (err) throw err;
        console.log(data.toString('utf8'));
    });
});
In the code above, we will write to the file mynewfile2.txtThere are two functions fsthat we use:
  • fs.writeFile() to write to file;
  • and fs.readFile()to read files.
In the function fs.readFile(), we use a function toString('utf8')to convert the buffer to text by encoding UTF-8.
Now try executing the program:
Write and read files in Nodejs
As we expected, the file was successfully written and read.

Change the File Name with Nodejs

After we try to read and write files in Nodejs, next we try to rename the file.
In the module fsthere is a function rename() to change the name.
This function has three parameters:
  1. File name;
  2. New name;
  3. The function that will be executed when the name is changed.
Let's try ...
Create a new javascript file with the name rename.jsand fill in the following code:
var fs = require('fs');

fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
    if (err) throw err;
    console.log('File Renamed!');
}); 
After that, try executing the program:
Rename the file on nodejs

Deleting Files with Nodejs

The module fshas a function unlink()to delete files. This function has two parameters:
  1. The file name to be deleted;
  2. function that will be executed when the file is deleted.
Let's try ...
Make a new file named delete.js, then fill in the following code:
var fs = require('fs');

fs.unlink('mynewfile2.txt', function (err) {
    if (err) throw err;
    console.log('File deleted!');
}); 
In the program code above, we will delete the file mynewfile2.txtLet's try execution:
Delete files with nodejs

0 Komentar untuk "Learning Nodejs # 5: How to Use the File System Module to Read Write Files"

Silahkan berkomentar sesuai artikel

 
Copyright © 2015 - 2024 Blog for Learning - All Rights Reserved
Template By Kunci Dunia
Back To Top