लोड हो रहा है...

Common errors और fixes

Node.js में Common errors और उनके fixes को समझना किसी भी डेवलपर के लिए अत्यंत महत्वपूर्ण है। Node.js की asynchronous और event-driven प्रकृति के कारण, अक्सर developers syntax errors, unhandled exceptions, memory leaks और inefficient algorithms जैसी समस्याओं का सामना करते हैं। इन errors को समय पर पहचानना और उनका समाधान करना application की stability और performance के लिए जरूरी है।
Node.js development में Common errors और fixes का उपयोग तब किया जाता है जब कोई asynchronous operation, file I/O, डेटा structure manipulation या algorithm implementation सही तरीके से काम नहीं कर रहा हो। इसके लिए Node.js के core concepts जैसे syntax, data structures, algorithms और OOP principles की अच्छी समझ होना आवश्यक है।

मूल उदाहरण

text
TEXT Code
const fs = require('fs');

function readFileSafely(path) {
try {
const data = fs.readFileSync(path, 'utf8');
console.log('File content:', data);
} catch (err) {
console.error('File read error:', err.message);
}
}

readFileSafely('./example.txt');

उपरोक्त उदाहरण Node.js में सुरक्षित file reading का बेसिक pattern दिखाता है। readFileSafely function fs.readFileSync को try/catch block में wrap करता है, जिससे file missing या permission errors जैसी समस्याओं को gracefully handle किया जा सके।
console.log और console.error का उपयोग debugging और error logging के लिए किया गया है। यह pattern memory leaks और unhandled exceptions जैसी सामान्य गलतियों से बचाता है। प्रैक्टिकल applications में इस approach को asynchronous operations, database calls या API integrations में भी extend किया जा सकता है।

व्यावहारिक उदाहरण

text
TEXT Code
class UserManager {
constructor() {
this.users = [];
}

addUser(user) {
if (!user || !user.name) {
throw new Error('Invalid user data');
}
this.users.push(user);
}

findUser(name) {
return this.users.find(u => u.name === name) || null;
}

}

const manager = new UserManager();

try {
manager.addUser({ name: 'Ravi', age: 28 });
console.log(manager.findUser('Ravi'));
manager.addUser({ age: 25 }); // Intentional error
} catch (err) {
console.error('User management error:', err.message);
}

Advanced Node.js Implementation

text
TEXT Code
const EventEmitter = require('events');

class TaskManager extends EventEmitter {
constructor() {
super();
this.tasks = [];
}

addTask(task) {
if (!task || !task.id) {
this.emit('error', new Error('Invalid task'));
return;
}
this.tasks.push(task);
this.emit('taskAdded', task);
}

removeTask(id) {
const index = this.tasks.findIndex(t => t.id === id);
if (index === -1) {
this.emit('error', new Error('Task not found'));
return;
}
const removed = this.tasks.splice(index, 1);
this.emit('taskRemoved', removed[0]);
}

}

const manager = new TaskManager();

manager.on('taskAdded', t => console.log('Task added:', t));
manager.on('taskRemoved', t => console.log('Task removed:', t));
manager.on('error', err => console.error('Error detected:', err.message));

manager.addTask({ id: 1, title: 'Learn Node.js' });
manager.addTask({ title: 'Task without ID' });
manager.removeTask(2);

यह pattern array algorithms, conditional checks और production-ready architecture के लिए applicable है। इसे asynchronous APIs, microservices या backend workflows में भी इस्तेमाल किया जा सकता है, जिससे scalable और maintainable Node.js applications बनती हैं।

📊 संपूर्ण संदर्भ

fs.readFileSync Reads a file synchronously fs.readFileSync(path, encoding) const data = fs.readFileSync('file.txt', 'utf8'); Prefer async version for large files
fs.writeFileSync Writes a file synchronously fs.writeFileSync(path, data) fs.writeFileSync('file.txt', 'Hello'); Prefer async version
fs.existsSync Checks file existence fs.existsSync(path) if(fs.existsSync('file.txt')){} Avoid race conditions
Array.push Adds element to array array.push(element) arr.push(5); Avoid duplicates
Array.find Find element in array array.find(callback) arr.find(x => x.id===1); Returns null if not found
console.log Logs info console.log(value) console.log('Hello'); For debugging only
console.error Logs errors console.error(value) console.error('Error'); Prefer production logging
require Imports module require('module') const fs = require('fs'); At the top of file
EventEmitter.emit Emits an event emitter.emit(event, args) emitter.emit('event', data); Handle errors gracefully
EventEmitter.on Listens to event emitter.on(event, callback) emitter.on('event', data => {}); Log important error events
Error Creates error object new Error(message) throw new Error('Error'); Use with try/catch or events
JSON.parse Parses JSON string JSON.parse(string) const obj = JSON.parse(jsonString); Validate inputs
JSON.stringify Converts object to JSON JSON.stringify(obj) const str = JSON.stringify(obj); For storage or transmission
setTimeout Executes function after delay setTimeout(callback, ms) setTimeout(() => {}, 1000); Avoid blocking code
setInterval Executes function repeatedly setInterval(callback, ms) setInterval(() => {}, 1000); Use clearInterval to prevent leaks
process.on('uncaughtException') Handles unhandled exceptions process.on('uncaughtException', callback) process.on('uncaughtException', err => {}); Log and optionally exit

📊 Complete Node.js Properties Reference

Property Values Default Description Node.js Support
readFileSync path, encoding none Reads file synchronously All versions
writeFileSync path, data, encoding none Writes file synchronously All versions
existsSync path false Checks file existence All versions
push element none Adds element to array All versions
find callback none Finds element in array All versions
console.log value none Logs information All versions
console.error value none Logs errors All versions
require moduleName none Imports module All versions
EventEmitter.emit event, args none Emits event All versions
EventEmitter.on event, callback none Listens to event All versions
JSON.parse string none Parses JSON string All versions
JSON.stringify object none Converts object to JSON All versions

Summary और next steps: Common errors और fixes सीखने से developers robust, maintainable और high-performance Node.js applications बना सकते हैं। Errors और exceptions को समझना, event-driven patterns, OOP और asynchronous operations में proficiency बढ़ाता है।
अगले steps में asynchronous optimization, database integration, microservices design और CI/CD deployment शामिल हैं। इन techniques का उपयोग production में bugs कम करता है और stable applications सुनिश्चित करता है। Community resources और official documentation से learning को continue किया जा सकता है।

🧠 अपने ज्ञान की परीक्षा करें

शुरू करने के लिए तैयार

अपने ज्ञान की परीक्षा करें

इस इंटरैक्टिव क्विज़ के साथ अपनी चुनौती लें और देखें कि आप विषय को कितनी अच्छी तरह समझते हैं

4
प्रश्न
🎯
70%
पास करने के लिए
♾️
समय
🔄
प्रयास

📝 निर्देश

  • हर प्रश्न को ध्यान से पढ़ें
  • हर प्रश्न के लिए सबसे अच्छा उत्तर चुनें
  • आप जितनी बार चाहें क्विज़ दोबारा दे सकते हैं
  • आपकी प्रगति शीर्ष पर दिखाई जाएगी