File System Module

Node.js File System Module is a powerful tool that allows developers to interact with the file system on their computer. It can be used to perform many operations such as reading, creating, updating, deleting, renaming, and uploading files. This guide provides an overview of how to use the File System Module in Node.js, complete with examples to illustrate each operation.

Node.js as a File Server

Node.js can be transformed into a file server, making it possible to serve static files to a web browser, similar to how Apache or Nginx works. This is useful for serving websites or any type of file. Node.js, combined with the File System Module and the HTTP module, can serve HTML, image files, scripts, and more.

1. Read Files

To read files in Node.js, you use the fs.readFile() method. This method reads the content of a file and returns its contents. It’s an asynchronous operation, meaning that Node.js can perform other tasks while reading the file.

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(data);
});

In this example, example.txt is the file we’re reading, and 'utf8' specifies the encoding. If the reading is successful, the content of the file is logged to the console.

2. Create Files

Node.js can create files using methods like fs.writeFile() or fs.appendFile(). fs.writeFile() creates a new file if the specified file does not exist, writing the specified content. If the file exists, it will overwrite the content.

const fs = require('fs');

fs.writeFile('newfile.txt', 'Hello, world!', (err) => {
  if (err) throw err;
  console.log('File created and content written!');
});

This code snippet creates a file named newfile.txt and writes Hello, world! as its content.

3. Update Files

To update a file, you can use fs.appendFile() to append content to the end of a file or fs.writeFile() to overwrite the existing content.

const fs = require('fs');

fs.appendFile('example.txt', ' This is new content.', (err) => {
  if (err) throw err;
  console.log('Updated file with new content!');
});

This adds This is new content. to the end of example.txt.

4. Delete Files

To delete a file, use the fs.unlink() method. It removes the file from the filesystem.

const fs = require('fs');

fs.unlink('file-to-delete.txt', (err) => {
  if (err) throw err;
  console.log('File deleted!');
});

Here, file-to-delete.txt will be removed from the filesystem.

5. Rename Files

To rename a file, the fs.rename() method is used. This can also move the file to a different directory.

const fs = require('fs');

fs.rename('oldname.txt', 'newname.txt', (err) => {
  if (err) throw err;
  console.log('File renamed!');
});

This changes the name of oldname.txt to newname.txt.

6. Upload Files

File upload is a bit more complex as it usually involves working with web forms and multipart/form-data. However, with additional packages like multer or formidable, handling file uploads becomes easier.

Here’s a basic example using formidable:

const http = require('http');
const formidable = require('formidable');

http.createServer((req, res) => {
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, (err, fields, files) => {
      var oldpath = files.filetoupload.filepath;
      var newpath = '/uploads/' + files.filetoupload.originalFilename;
      fs.rename(oldpath, newpath, (err) => {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
    });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
}).listen(8080);

In this example, a simple server is created that listens on port 8080. It uses formidable to handle file uploads. Users can upload files through a form