Day 1 of Learning Node.js

PUBLISHED: MAY 2, 20266 MIN READ

Node.js is a runtime environment that lets you run JavaScript outside the browser. You use it because it’s fast, scalable, and efficient for I/O-heavy tasks. It

Divya Sachan
Divya SachanAuthor
toxicroak
#454
toxicroak

Node.js is a runtime environment that lets you run JavaScript outside the browser. You use it because it’s fast, scalable, and efficient for I/O-heavy tasks. It’s best applied when building real-time applications, APIs, or services that handle many concurrent requests.

📌 What is Node.js?

  • Definition: Node.js is an open-source, cross-platform runtime built on Chrome’s V8 JavaScript engine. It allows developers to run JavaScript on the server side, not just in the browser.
  • Core Idea: It uses a single-threaded, event-driven architecture with non-blocking I/O, meaning it can handle thousands of requests simultaneously without waiting for one to finish before starting another.
  • Ecosystem: Comes with npm (Node Package Manager), the largest ecosystem of open-source libraries, making development faster and easier.

💡 Why use Node.js?

  • Performance: Compiles JavaScript to machine code via the V8 engine, making it extremely fast for tasks like file handling, APIs, and network requests.
  • Scalability: Perfect for applications that need to handle high traffic (e.g., Netflix reduced startup time by 70% after adopting Node.js).
  • Unified Language: Developers can use JavaScript for both frontend and backend, simplifying full-stack development.
  • Community & Adoption: Widely used by companies like PayPal, LinkedIn, Uber, Yahoo, Medium, GoDaddy, Groupon, and Walmart.
  • Real-time Capabilities: Excellent for apps requiring instant communication (e.g., chat apps, online gaming) thanks to WebSockets.

⏰ When to use Node.js?

Ideal Scenarios

  • Real-time applications
    • Chat apps, online gaming, collaborative tools.
    • Node.js supports WebSockets for two-way communication between client and server.
  • APIs & Microservices
    • RESTful or GraphQL APIs that handle thousands of requests simultaneously.
    • Non-blocking I/O makes Node.js highly efficient for backend services.
  • Streaming services
    • Video/audio platforms like Netflix use Node.js for smooth streaming.
    • Its event-driven model handles continuous data flow without delays.
  • Single-page applications (SPAs)
    • Frameworks like React or Angular pair well with Node.js for backend logic.
    • Developers can use JavaScript end-to-end (frontend + backend).
  • IoT (Internet of Things)
    • Lightweight and event-driven, Node.js is perfect for devices sending frequent, small data packets.
  • High-traffic websites
  • Companies like PayPal, LinkedIn, and Walmart rely on Node.js to serve millions of users efficiently.

⚠️ When NOT to Use Node.js

  • CPU-intensive tasks
    • Heavy image processing, machine learning training, or complex mathematical computations.
    • Node.js is single-threaded, so such tasks can block the event loop.
    • Applications requiring strict synchronous processing
    • Financial systems or apps where operations must run sequentially without interruption.
    • Languages like Java or Python may be better suited.

  • CPU-intensive tasks (e.g., heavy image processing, complex mathematical computations) → Node.js is single-threaded, so such tasks can block the event loop.
  • Applications requiring strict synchronous processing → Better suited for languages like Java or Python in those cases.

1. Importing the fs module

const fs = require('fs');

  • Node.js provides the fs module to interact with the file system.
  • It allows you to create, read, update, and delete files (CRUD operations).
  • require('fs') loads this module so you can use its methods.

2. Create a File

fs.writeFileSync('student.txt', 'Naveen, Gupta');

  • writeFileSync creates a new file (or overwrites if it already exists).
  • Parameters:
    • 'student.txt' → filename
    • 'Naveen, Gupta' → content written inside the file
  • The Sync means synchronous execution: Node.js will block further code until this operation finishes.

3. Read a File

console.log(fs.readFileSync('student.txt', 'utf8'));

  • readFileSync reads the file content.
  • 'utf8' specifies the encoding (so you get text instead of raw bytes).
  • Output: Naveen, Gupta

4. Update a File

fs.appendFileSync('student.txt', ', Pallu');

  • appendFileSync adds new content at the end of the file.
  • After this, file content becomes: Naveen, Gupta, Pallu

5. Delete a File

fs.unlinkSync('student.txt');

  • unlinkSync deletes the file permanently.
  • After this, student.txt no longer exists.

📘 Theory to Enhance Your Knowledge

Synchronous vs Asynchronous

  • You used synchronous methods (writeFileSync, readFileSync, etc.).
  • These block the event loop until the operation completes.
  • For real-world applications, asynchronous methods (writeFile, readFile, etc.) are preferred because they don’t block other tasks.

Example (async):

fs.writeFile('student.txt', 'Hello World', (err) => { if (err) throw err; console.log('File created!'); });

Node.js Core Concepts

  • Single-threaded, non-blocking I/O: Node.js uses an event loop to handle multiple tasks efficiently.
  • Modules: fs is a core module. You can also create your own modules.
  • Callbacks & Promises: Asynchronous operations often use callbacks or modern async/await.

File System Operations (CRUD)

writeFileSyncwriteFile
readFileSyncreadFile
appendFileSyncappendFile
unlinkSyncunlink

Best Practices

  • Use async methods in production.
  • Always handle errors (try...catch for sync, error callbacks for async).
  • Organize file operations logically (e.g., check if file exists before reading).

✅ You’ve already touched on CRUD with files, which is a fundamental building block in Node.js. Next steps could be:

  • Explore directories (fs.mkdir, fs.readdir).
  • Learn about streams (fs.createReadStream, fs.createWriteStream) for handling large files efficiently.
  • Practice async/await with file operations.