Skip to content

The fs module

fs.readFile()

Task 1: Create a simple nodejs file, and add the fs module to it. Hint: use the require statement.

const fs = require('fs');

Task 2: Create a folder in the current working directory, and call it "myfiles". Create a file in that folder, and call it "file.txt". Add the following text to that file.

Hello there!
Hope life is treating you well today!

Task 3: Check the following code.

const fs = require('fs');
const path = require('path');

let fileToRead = path.join(__dirname, 'myfiles', 'file.txt');
fs.readFile(fileToRead, "utf-8", function(err, content){
    if (err) throw err;
    console.log(content);
});

If you have not created the folder and the file in task 2, you will get an error while trying to execute task 3.

[Error: ENOENT: no such file or directory, open '/dir/to/myfiles/file.txt']

If no errors occurred, the file content will be displayed:

Hello there!
Hope life is treating you well today!

fs.readFile()

The fs.readFile(filename, encoding, (err, data) => {}) method reads a given file. It takes the filename, encoding, and a callback function. The callback function takes two parameters: err in case an error occurs and data which holds the file content.

Task 4: Create another file in "myfiles", call it "style.css". And the following content to it. Then, read this file using the fs module.

// myfiles/style.css
body, html{
    height: 100%;
}

.container{
    display: flex;
    flex-direction: column;
    align-items: center;
    background: tomato;
    color: #fffff;
    padding: 1rem;
}
const fs = require('fs');
const path = require('path');

let fileToRead = path.join(__dirname, 'myfiles', 'style.css');
fs.readFile(fileToRead, "utf-8", function(err, content){
    if (err) throw err;
    console.log(content);
});

The content of the file will be logged in the console.

Task 5: Create another file in "myfiles", call it "script.js". And the following content to it. Then, read this file using the fs module.

//myfiles/script.js
let sum = (a, b) => a + b;

let result = sum(5, 7);
const fs = require('fs');
const path = require('path');

let fileToRead = path.join(__dirname, 'myfiles', 'script.js');
fs.readFile(fileToRead, "utf-8", function(err, content){
    if (err) throw err;
    console.log(content);
});

The content of the file will be logged in the console.

fs.mkdir()

Task 6: Check the following code.

const fs = require('fs');
const path = require('path');

fs.mkdir(path.join(__dirname, 'static'), (err) => {
    if (err) throw err;
    console.log(`The directory is successfuly created.`);
});

If no error occurs, you will see The directory is successfully created. in the console.

fs.mkdir()

The fs.mkdir(directory_name, (err) => {}) method creates a new directory. It takes the directory name and a callback function. The callback function takes the err parameter in case an error occurs.

Task 7: Create a new direcotry, and call it "public" using the fs.mkdir() method.

const fs = require('fs');
const path = require('path');

fs.mkdir(path.join(__dirname, 'public'), (err) => {
    if (err) throw err;
    console.log(`The directory is successfully created.`);
});

If no error occurs, you will see The directory is successfully created. in the console.

fs.rmdir()

Task 8: Delete the "static" directory using the fs.rmdir() method.

const fs = require('fs');
const path = require('path');

fs.rmdir(path.join(__dirname, 'static'), (err) => {
    if (err) throw err;
    console.log(`The directory is deleted successfuly.`);
});

If no error occurs, you will see The directory is deleted successfuly in the console.

Task 9: Delete the "public" directory using the fs.rmdir() method.

const fs = require('fs');
const path = require('path');

fs.rmdir(path.join(__dirname, 'public'), (err) => {
    if (err) throw err;
    console.log(`The directory is deleted successfuly.`);
});

If no error occurs, you will see The directory is deleted successfuly in the console.

fs.rmdir()

The fs.rmdir(directory_name, (err) => {}) method removes a directory. It takes the directory name and a callback function. The callback function takes the err parameter in case an error occurs.

fs.writeFile()

Task 10: Check the following code.

const fs = require('fs');
const path = require('path');

fs.writeFile(path.join(__dirname, 'newfile.txt'), "Hi there", {encoding: "utf-8"}, (err) => {
    if (err) throw err;
    console.log("The file is created successfully.");
});

If no error occurs, you will see The file is created successfully in the console. And a new file with the name "newfile.txt" was created, and its content is "Hello there".

fs.writeFile()

The fs.writeFile(file, data, options, callback) method writes data to a file. It takes "the file name", "the data to add to the file", options {encoding: "utf8"}, and a callback function. The callback function takes an err parameter in case an error occurs.

Task 11: Create a new file, and call it "hello.txt". Add "I salute and welcome each and every one of you. YAY!".

const fs = require('fs');
const path = require('path');

fs.writeFile(path.join(__dirname, 'hello.txt'), "I salute and welcome each and every one of you. YAY!", {encoding: "utf-8"}, (err) => {
    if (err) throw err;
    console.log("The file is created successfully.");
});

If no error occurs, you will see The file is created succesfully in the console. And a new file with the name "hello.txt" was created, and its content is "HI salute and welcome each and every one of you. YAY".

Task 12: Delete the newfile.txt file created in task 10. Hint: use the fs.unlink() method.

const fs = require('fs');
const path = require('path');

fs.unlink(path.join(__dirname, 'newfile.txt'), (err) => {
    if (err) throw err;
    console.log("The file is deleted successfully.");
});

If no error occurs, the file "newfile.txt" will be deleted.

fs.unlink()

The method fs.unlink(file, (err) => {}) method removes a file with the provided the filename. It takes the "filename" and "a callback function" as parameters. The callback function takes an err in case an error occurs.

Task 13: Delete the hello.txt file created in task 11.

const fs = require('fs');
const path = require('path');

fs.unlink(path.join(__dirname, 'hello.txt'), (err) => {
    if (err) throw err;
    console.log("The file is deleted successfully.");
});

If no error occurs, the file "hello.txt" will be deleted.

Mini Projects

Project 1

Task 14: Create the following directory tree using nodejs.

./
├─ public/
│  ├─ css/
│  │  ├─ style.css
│  ├─ scripts/
│  │  ├─ script.js
│  ├─ index.html
const fs = require('fs');
const path = require('path');

fs.mkdir(path.join(__dirname, "public"), (err) => {
    if (err) throw err;
    console.log("The directory public has been created");
});

fs.mkdir(path.join(__dirname, "public", "css"), (err) => {
    if (err)  throw err;
    console.log("The directory css has been created");
});

fs.mkdir(path.join(__dirname, "public", "scripts"), (err) => {
    if (err)  throw err;
    console.log("The directory scripts has been created");
});

fs.writeFile(path.join(__dirname, "public/css", "style.css"), "", (err) => {
    if (err) throw err;
    console.log("The file style.css has been created");
});

fs.writeFile(path.join(__dirname, "public/scripts", "script.js"), "", (err) => {
    if (err) throw err;
    console.log("The file script.js has been created");
});

Project 2

Task 15: Create a simple nodejs server. Show the following "index.html" in the browser.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>my website</title>
</head>
<body>
    <h1>welcome to my website</h1>
</body>
</html>
const http = require("http");
const path = require("path");
const fs = require("fs");

const server = http.createServer((req, res) => {
    fs.readFile(path.join(__dirname, "public/index.html"), "utf8", (err, content) => {
        if (err) throw err;
        res.writeHead(200, {"Content-Type": "text/html"});
        res.end(content);
    }); 
});

server.listen(9000);