Node.js Tutorial
Estimated reading: 4 minutes 25 views

๐Ÿงฐ Node.js File & Server Operations โ€“ Handle Files, Uploads, Emails, and HTTP with Ease

๐Ÿงฒ Introduction โ€“ Manage Files and Servers Like a Pro with Node.js

Node.js offers robust capabilities for file handling and server communication through built-in and third-party modules. From reading local files to building HTTP servers, sending emails, and managing file uploadsโ€”Node.js provides both low-level control and high-level simplicity.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to use the fs module to read/write/delete files
  • How to handle file uploads in Node.js
  • How to send emails using third-party modules
  • How to create HTTP servers and parse URLs

๐Ÿ“˜ Topics Covered

๐Ÿ”น Topic๐Ÿ“– Description
๐Ÿ“ Node.js โ€“ File System ModuleUse fs module to read, write, rename, and delete files and directories
โฌ†๏ธ Node.js โ€“ Uploading FilesAccept and store uploaded files from HTML forms
โœ‰๏ธ Node.js โ€“ Sending EmailsSend emails using SMTP with nodemailer
๐Ÿ”— Node.js โ€“ HTTP & URL ModulesCreate web servers and parse incoming request URLs

๐Ÿ“ Node.js โ€“ File System Module (fs)

Node.js provides the fs (File System) module for interacting with the local file system.

๐Ÿ”น Read File Asynchronously

const fs = require('fs');

fs.readFile('demo.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

๐Ÿ”น Write to a File

fs.writeFile('output.txt', 'Hello Node.js!', (err) => {
  if (err) throw err;
  console.log('File saved!');
});

๐Ÿ”น Delete a File

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

๐Ÿงช Output:

Hello Node.js!
File saved!
File deleted!

โœ… The fs module supports both async and sync versions (fs.readFileSync, fs.writeFileSync).


โฌ†๏ธ Node.js โ€“ Uploading Files

To handle file uploads, you can use the formidable or multer module. Hereโ€™s a basic example with formidable.

npm install formidable

๐Ÿ”น HTML Upload Form

<form action="upload" method="post" enctype="multipart/form-data">
  <input type="file" name="fileupload">
  <input type="submit">
</form>

๐Ÿ”น Upload Handler (Node.js)

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

http.createServer((req, res) => {
  if (req.url === '/upload' && req.method === 'POST') {
    const form = new formidable.IncomingForm();
    form.parse(req, (err, fields, files) => {
      const oldPath = files.fileupload.filepath;
      const newPath = './uploads/' + files.fileupload.originalFilename;

      fs.rename(oldPath, newPath, () => {
        res.write('File uploaded and moved!');
        res.end();
      });
    });
  }
}).listen(3000);

๐Ÿงช Output:

File uploaded and moved!

โœ… Make sure the uploads directory exists in your project.


โœ‰๏ธ Node.js โ€“ Sending Emails

To send emails in Node.js, use the nodemailer module.

npm install nodemailer

๐Ÿ”น Basic Email Example

const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'your_email@gmail.com',
    pass: 'your_password'
  }
});

let mailOptions = {
  from: 'your_email@gmail.com',
  to: 'recipient@example.com',
  subject: 'Node.js Email Test',
  text: 'This email was sent using Node.js!'
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) throw error;
  console.log('Email sent: ' + info.response);
});

๐Ÿงช Output:

Email sent: 250 2.0.0 OK

โœ… Use app-specific passwords and secure configs when deploying.


๐Ÿ”— Node.js โ€“ HTTP & URL Modules

Node.js lets you build servers and parse URLs without frameworks.

๐Ÿ”น Create a Basic Server

const http = require('http');

http.createServer((req, res) => {
  res.write('Welcome to Node.js Server!');
  res.end();
}).listen(3000);

๐Ÿ”น Parse URL and Query String

const url = require('url');

http.createServer((req, res) => {
  const q = url.parse(req.url, true).query;
  res.write('Hello ' + (q.name || 'Guest'));
  res.end();
}).listen(3000);

๐Ÿงช Output:

Visit: http://localhost:3000/?name=John
โ†’ Hello John

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

Node.js simplifies file management and server operations using built-in and third-party tools. With just a few lines of code, you can read files, host web servers, upload content, and send emailsโ€”all asynchronously and efficiently.

๐Ÿ” Key Takeaways:

  • fs module handles file reading/writing/deleting
  • File uploads are handled using formidable or multer
  • nodemailer allows SMTP-based email sending
  • http and url modules build custom web servers without Express

โš™๏ธ Real-World Uses:

  • File upload APIs for cloud storage apps
  • Email notifications in registration systems
  • Static site file serving and templating
  • Simple chat or dashboard servers

โ“ Frequently Asked Questions

โ“ How do I read a file in Node.js?
โœ… Use fs.readFile(filename, 'utf8', callback) to read a file asynchronously.


โ“ How to upload files to a server using Node.js?
โœ… Use modules like formidable or multer to parse incoming form data and move files.


โ“ Can Node.js send emails without a server?
โœ… Yes, using nodemailer, you can send SMTP emails via Gmail or another mail service.


โ“ Whatโ€™s the difference between fs and http modules?
โœ… fs is for file system operations; http is for creating servers and handling web requests.


โ“ How to parse URL parameters in Node.js?
โœ… Use url.parse(req.url, true).query to extract query strings like ?name=John.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿงฐ Node.js File & Server Operations

Or Copy Link

CONTENTS
Scroll to Top