Creating Server in nodejs & File System In Node js

Creating a server in Node.js is straightforward, thanks to the built-in http module. Below is a step-by-step guide to setting up a simple HTTP server.

    var http = require('http');

    //create a server object:
    http.createServer(function (req, res) {
    res.write('Hello World!'); //write a response to the client
    res.end(); //end the response
    }).listen(8080); //the server object listens on port 8080

File System module:
  • Read files
  • Create files
  • Update files
  • Delete files
  • Rename files

Read Files

The fs.readFile() method is used to read files on your computer. Assume we have the following HTML file (located in the same folder as Node.js):

Index.html file

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

App. js file

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

res.writeHead(200, {'Content-Type': 'text/html'});

is a method call used in Node.js to set the status code and response headers of an HTTP response. Here's a breakdown of what it does:

200: This is the HTTP status code for "OK," indicating that the request has been successfully processed. {'Content-Type': 'text/html'}: This is an object specifying the headers for the HTTP response. In this case: Content-Type is set to text/html, which informs the client (e.g., a browser) that the response content will be HTML.

Read Files, with Synchronous note pad File Read.

The fs.readFile() method is used to read files on your computer. Synchronous File Read ,This blocks the execution of the code until the file is read:

    const fs = require('fs');

    try {
    const data = fs.readFileSync('myrenamedfile.txt', 'utf8');
    console.log(data);
    } catch (err) {
    console.error('Error reading file:', err);
    }

Create Files

The File System module has methods for creating new files:

  • fs.appendFile()
  • fs.open()
  • fs.writeFile()

fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be created:

    var fs = require('fs');

    fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
    if (err) throw err;
    console.log('Saved!');
    });

fs.open() method takes a "flag" as the second argument, if the flag is "w" for "writing", the specified file is opened for writing. If the file does not exist, an empty file is created:

    var fs = require('fs');

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

fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created:

    var fs = require('fs');

    fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
    if (err) throw err;
    console.log('Replaced!');
    });

Delete Files

To delete a file with the File System module,  use the fs.unlink() method. The fs.unlink() method deletes the specified file:

    var fs = require('fs');

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

Rename Files

To rename a file with the File System module,  use the fs.rename() method. The fs.rename() method renames the specified file:

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