Util মডিউল কি?
Util মডিউল হল একটি কোর Node.js মডিউল যা সাধারণ কাজের জন্য ইউটিলিটি ফাংশনগুলির একটি সেট প্রদান করে।
এটি Node.js ডেভেলপারদের জন্য একটি সুইস আর্মি ছুরির মতো, যেমন সমাধানগুলি অফার করে:
সাধারণ ব্যবহারের ক্ষেত্রে
স্থানধারক সহ স্ট্রিং বিন্যাস
স্ট্রিং বিন্যাস এবং প্রতিস্থাপন
ডিবাগিংয়ের জন্য বস্তু পরীক্ষা করা হচ্ছে
উপাদান বিশ্লেষণ এবং উপস্থাপনা
কলব্যাক এবং প্রতিশ্রুতি মধ্যে স্যুইচিং
অ্যাসিঙ্ক্রোনাস কোড রূপান্তর
টাইপ পরীক্ষা এবং বৈধতা
ডেটা টাইপ যাচাইকরণ
পরিত্যক্ত সতর্কতা পরিচালনা করা
API পরিত্যাগ ব্যবস্থাপনা
ডিবাগিং এবং লগিং
ডিবাগিং এবং লগিং কৌশল
মূল সুবিধা
দ্রষ্টব্য:
Util মডিউলের কিছু ফাংশন Node.js-এর অভ্যন্তরীণ ব্যবহারের উদ্দেশ্যে তৈরি করা হয়েছে, কিন্তু অনেকগুলি Node.js অ্যাপ্লিকেশন তৈরি করার জন্য ডেভেলপারদের জন্য মূল্যবান টুল।
মডিউলটি Node.js এর সাথে অন্তর্ভুক্ত, তাই কোন ইনস্টলেশনের প্রয়োজন নেই।
Util দিয়ে শুরু করা
এখানে একটি ব্যবহারিক উদাহরণ রয়েছে যা ইউটিল মডিউল থেকে বেশ কয়েকটি অ্যাপ্লিকেশানকে কর্মে প্রদর্শন করে:
বেসিক অ্যাপ্লিকেশন উদাহরণ
const util = require('util');
const fs = require('fs');
// Convert callback-based fs.readFile to Promise-based
const readFile = util.promisify(fs.readFile);
// Format strings with placeholders
const greeting = util.format('Hello, %s! Today is %s', 'Developer', new Date().toDateString());
console.log(greeting);
// Inspect an object with custom options
const obj = {
name: 'Test',
nested: { a: 1, b: [2, 3] },
fn: function() { return 'test'; }
};
console.log(util.inspect(obj, { colors: true, depth: 2 }));
// Use debug logging
const debug = util.debuglog('app');
debug('This will only show if NODE_DEBUG=app');
// Example of using promisify with async/await
async function readConfig() {
try {
const data = await readFile('package.json', 'utf8');
console.log('Package name:', JSON.parse(data).name);
} catch (err) {
console.error('Error reading config:', err);
}
}
readConfig();
আমদানি এবং স্থাপন
আপনি আপনার মডিউল সেটআপ এবং প্রয়োজনীয়তার উপর নির্ভর করে বিভিন্ন উপায়ে Util মডিউল আমদানি করতে পারেন:
CommonJS (Node.js ডিফল্ট)
// Import the entire module
const util = require('util');
// Import specific functions using destructuring
const { promisify, inspect, format } = require('util');
// Using strict mode (recommended)
const assert = require('assert').strict;
// For TypeScript users
// import * as util from 'util';
// import { promisify, inspect } from 'util';
ES Modules (Node.js 12+)
// Default import
import util from 'util';
// Named imports
import { promisify, inspect } from 'util';
// Rename imports
import { promisify as pify } from 'util';
// Dynamic import (Node.js 14+)
const { promisify } = await import('util');
// Using with TypeScript types
// import * as util from 'util';
// import type { InspectOptions } from 'util';
সর্বোত্তম অনুশীলন:
ভাল গাছ-কাঁপানো এবং ছোট বান্ডিলগুলির জন্য, শুধুমাত্র আপনার প্রয়োজনীয় ফাংশনগুলিতে বিনাশকারী আমদানি পছন্দ করুন।
Util মডিউলটি বেশ বড়, এবং আপনি সাধারণত এর কার্যকারিতার একটি ছোট উপসেট ব্যবহার করেন।
স্ট্রিং নকশা এবং পরিদর্শন
Util মডিউল স্ট্রিং ফরম্যাটিং এবং অবজেক্ট পরিদর্শন করার জন্য শক্তিশালী টুল সরবরাহ করে, যা লগিং এবং ডিবাগিংয়ের জন্য বিশেষভাবে কার্যকর।
util.format(format[, ...args])
printf-এর মতো ফরম্যাট স্ট্রিং হিসেবে প্রথম আর্গুমেন্ট ব্যবহার করে একটি ফরম্যাট করা স্ট্রিং ফেরত দেয়।
এটি console.log() এর অনুরূপ, তবে এটি প্রিন্ট করার পরিবর্তে একটি ফর্ম্যাট করা স্ট্রিং প্রদান করে।
ফর্ম্যাট স্পেসিফায়ার:
| উল্লেখ | ব্যাখ্যা |
|---|---|
| %s | স্ট্রিং |
| %d | সংখ্যা (পূর্ণসংখ্যা এবং ভাসমান উভয়) |
| %i | পূর্ণসংখ্যা |
| %f | ফ্লোটিং পয়েন্ট মান |
| %j | JSON (যদি যুক্তিতে বৃত্তাকার উদ্ধৃতি থাকে তবে '[সার্কুলার]' দিয়ে প্রতিস্থাপিত হয়) |
| %o | বিষয় (বিষয় পরীক্ষা করুন) |
| %O | বিষয় (সম্পূর্ণ বিবরণ সহ বিষয় পরীক্ষা করুন) |
| %% | একক শতাংশ চিহ্ন ('%') |
const util = require('util');
// Basic formatting
const formatted = util.format('Hello, %s!', 'World');
console.log(formatted); // 'Hello, World!'
// Multiple placeholders
const multiFormatted = util.format(
'My name is %s. I am %d years old and I love %s.',
'Kai',
30,
'Node.js'
);
console.log(multiFormatted);
// 'My name is Kai. I am 30 years old and I love Node.js.'
// Available specifiers
const specifiers = util.format(
'String: %s, Number: %d, JSON: %j, Character: %c',
'hello',
42,
{ name: 'Object' },
65 // ASCII code for 'A'
);
console.log(specifiers);
// Extra arguments are concatenated with spaces
const extra = util.format('Hello', 'World', 'from', 'Node.js');
console.log(extra); // 'Hello World from Node.js'
util.inspect(object[, options])
ডিবাগিংয়ের জন্য উপযোগী একটি বস্তুর একটি স্ট্রিং উপস্থাপনা প্রদান করে।
Node.js কনসোলে বস্তু মুদ্রণ করতে অভ্যন্তরীণভাবে এটি ব্যবহার করে।
সাধারণ ব্যবহারের ক্ষেত্রে:
- জটিল বস্তু ডিবাগ করা
- মানব-পাঠযোগ্য বস্তুর উপস্থাপনা তৈরি করা
- বৃত্তাকার উদ্ধৃতি দিয়ে বস্তু নিবন্ধন
- রেকর্ডে বস্তু প্রদর্শন কাস্টমাইজ করা
সাধারণ বিকল্প:
| বিকল্প | ব্যাখ্যা | ডিফল্ট |
|---|---|---|
| showHidden | অগণিত বৈশিষ্ট্য দেখান | false |
| depth | পুনরাবৃত্তি করার পর্যায়ের সংখ্যা | 2, null for unlimited |
| colors | ANSI রঙের কোড যোগ করুন | false |
| customInspect | কাস্টম পরিদর্শন ফাংশন ব্যবহার করুন | true |
| showProxy | প্রক্সি বিবরণ দেখান | false |
| maxArrayLength | অ্যারে উপাদান যোগ করার জন্য সর্বাধিক সংখ্যা | 100 |
| breakLength | যে দৈর্ঘ্যে বস্তুগত শক্তিগুলি অবশ্যই ভাঙতে হবে | 60 |
| compact | নতুন লাইনে বৈশিষ্ট্যগুলি ভাঙুন | true for arrays, false for objects |
| sorted | বাছাই বৈশিষ্ট্য | false, true for alphabetical, function for custom sort |
const util = require('util');
// Basic usage
const obj = {
name: 'John',
age: 30,
hobbies: ['reading', 'coding'],
address: {
city: 'New York',
country: 'USA'
},
toString() {
return `${this.name}, ${this.age}`;
}
};
// Default inspection
console.log(util.inspect(obj));
// Custom options
console.log(util.inspect(obj, {
colors: true, // Add ANSI color codes
depth: 0, // Only inspect the first level
showHidden: true, // Show non-enumerable properties
compact: false, // Don't format objects on a single line
showProxy: true, // Show proxy details
maxArrayLength: 3, // Limit array elements displayed
breakLength: 50, // Line break after 50 characters
sorted: true // Sort object properties alphabetically
}));
// Circular references
const circular = { name: 'Circular' };
circular.self = circular;
console.log(util.inspect(circular));
util.inspect.custom
বস্তুর বিশ্লেষণ কাস্টমাইজ করতে ব্যবহৃত একটি প্রতীক।
এটি পরীক্ষা করার সময় বস্তুকে তাদের নিজস্ব স্ট্রিং উপস্থাপনা সংজ্ঞায়িত করতে দেয়।
সর্বোত্তম অনুশীলন:
const util = require('util');
// Class with custom inspection
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
this._private = 'hidden information';
}
// Custom inspect method
[util.inspect.custom](depth, options) {
return `Person(${this.name}, ${this.age})`;
}
}
const kai = new Person('Kai', 30);
// Custom inspection is used
console.log(util.inspect(kai)); // Person(Kai, 30)
// Directly using console.log also uses custom inspection
console.log(kai); // Person(Kai, 30)
প্রতিশ্রুতি এবং অ্যাসিঙ্ক অ্যাপ্লিকেশন
Node.js Util , callback- Promise- API .
util.promisify(original)
Node.js callback callback- Promise .
এটি পুরানো Node.js APIগুলির সাথে কাজ করার জন্য দরকারী যা কলব্যাক ব্যবহার করে৷
util.promisify :
- পুরানো Node.js API এর সাথে কাজ করা যা কলব্যাক ব্যবহার করে
- প্রতিশ্রুতি ব্যবহার করতে কলব্যাক-ভিত্তিক লাইব্রেরি পরিবর্তন করা
- কলব্যাকগুলি সরিয়ে অ্যাসিঙ্ক/ওয়েট কোড সরলীকরণ করা হচ্ছে
- Node.js callback (error-first, single result)
সীমাবদ্ধতা:
- Node.js callback : (err, value) => {}
- কলব্যাকে একাধিক মান ফেরত দেয় এমন ফাংশনগুলির সাথে কাজ করে না
- আরও জটিল API-এর কাস্টম প্রতিশ্রুতি প্রয়োজন হতে পারে
const util = require('util');
const fs = require('fs');
// Convert fs.readFile from callback-based to Promise-based
const readFilePromise = util.promisify(fs.readFile);
// Now we can use it with async/await or Promise chaining
async function readFileExample() {
try {
// Using the promisified function
const data = await readFilePromise('package.json', 'utf8');
console.log('File content:', data.substring(0, 100) + '...');
// Error handling with try/catch
return 'File read successfully';
} catch (err) {
console.error('Error reading file:', err.message);
return 'Error reading file';
}
}
readFileExample().then(result => {
console.log('Result:', result);
});
util.callbackify(original)
যে ফাংশনটি প্রতিশ্রুতি প্রদান করে সেই ফাংশনে রূপান্তর করে যা Node.js কলব্যাক পদ্ধতি অনুসরণ করে।
এটি কলব্যাক-ভিত্তিক APIগুলির সাথে কাজ করার জন্য দরকারী যা কলব্যাক ফাংশন আশা করে।
util.callbackify :
- কলব্যাক-ভিত্তিক API-এর সাথে প্রতিশ্রুতি-ভিত্তিক কোড একীভূত করা
- লাইব্রেরিতে অনগ্রসর সামঞ্জস্য বজায় রাখা
- Node.js- callbacks API
- কলব্যাক থেকে প্রতিশ্রুতিতে ধীরে ধীরে স্থানান্তর
সর্বোত্তম অনুশীলন:
const util = require('util');
// A Promise-based function
async function fetchUserData(id) {
if (!id) {
throw new Error('ID is required');
}
// Simulate API request
return {
id,
name: `User ${id}`,
email: `user${id}@example.com`
};
}
// Convert to callback-based
const fetchUserDataCallback = util.callbackify(fetchUserData);
// Using the callback-based function
fetchUserDataCallback(1, (err, user) => {
if (err) {
console.error('Error:', err);
return;
}
console.log('User data:', user);
});
// Error handling
fetchUserDataCallback(null, (err, user) => {
if (err) {
console.error('Error occurred:', err.message);
return;
}
console.log('User data:', user); // This won't execute
});
util.promisify.custom
প্রতিশ্রুতি আচরণ কাস্টমাইজ করার জন্য প্রতীক। এটি আপনাকে একটি কাস্টম বাস্তবায়ন প্রদান করতে দেয় যখন একটি ফাংশন প্রতিশ্রুতিবদ্ধ হয়।
কাস্টম প্রতিশ্রুতি জন্য ক্ষেত্রে ব্যবহার করুন:
- যে ফাংশনগুলি একটি আদর্শ কলব্যাক পদ্ধতি অনুসরণ করে না
- API যেগুলি একটি কলব্যাকে একাধিক মান প্রদান করে৷
- কাস্টম ত্রুটি পরিচালনা বা ফলাফল পরিবর্তন
- নির্দিষ্ট ব্যবহারের ক্ষেত্রে কর্মক্ষমতা অপ্টিমাইজ করা
- প্রতিশ্রুতি দেওয়ার সময় অতিরিক্ত কার্যকারিতা যোগ করা
const util = require('util');
// Function with custom promisification
function doSomething(options, callback) {
callback(null, 'regular result');
}
// Define custom promisification
doSomething[util.promisify.custom] = (options) => {
return Promise.resolve('custom promisified result');
};
// Use the custom promisification
const promisified = util.promisify(doSomething);
// Compare the results
async function compareResults() {
// Original function with callback
doSomething({}, (err, result) => {
console.log('Callback result:', result);
});
// Custom promisified function
const customResult = await promisified({});
console.log('Promisified result:', customResult);
}
compareResults();
টাইপ পরীক্ষা অ্যাপ্লিকেশন
Util মডিউলটি JavaScript এর typeof অপারেটরের তুলনায় আরো নির্ভরযোগ্য বিস্তারিত টাইপ চেকিং ইউটিলিটি প্রদান করে, বিশেষ করে বিল্ট-ইন অবজেক্ট এবং Node.js-নির্দিষ্ট প্রকারের জন্য।
কেন util.types ব্যবহার করবেন?
const util = require('util');
// Example values
const values = [
'string',
123,
true,
Symbol('symbol'),
{ key: 'value' },
[1, 2, 3],
null,
undefined,
() => {},
BigInt(123),
new Date(),
/regex/,
Buffer.from('buffer'),
new Error('error')
];
// Check types for each value
values.forEach(value => {
console.log(`Value: ${util.inspect(value)}`);
console.log(`- isArray: ${util.types.isArrayBuffer(value)}`);
console.log(`- isDate: ${util.types.isDate(value)}`);
console.log(`- isRegExp: ${util.types.isRegExp(value)}`);
console.log(`- isNativeError: ${util.types.isNativeError(value)}`);
console.log(`- isPromise: ${util.types.isPromise(value)}`);
console.log(`- isPrimitive: ${util.isPrimitive(value)}`);
console.log(`- isString: ${util.isString(value)}`);
console.log(`- isNumber: ${util.isNumber(value)}`);
console.log(`- isBoolean: ${util.isBoolean(value)}`);
console.log(`- isSymbol: ${util.types.isSymbol(value)}`);
console.log(`- isNull: ${value === null}`);
console.log(`- isUndefined: ${value === undefined}`);
console.log(`- isFunction: ${util.types.isFunction(value)}`);
console.log(`- isBuffer: ${Buffer.isBuffer(value)}`);
console.log('---');
});
দ্রষ্টব্য:
util-এ টাইপ-চেকিং ফাংশনগুলির অনেকগুলি Array.isArray(), যেমন util.types বা JavaScript-এর অন্তর্নির্মিত টাইপ চেকিং পদ্ধতিগুলির অনুকূলে বাতিল করা হয়েছে।
util.types
util.types JavaScript Node.js- :
const util = require('util');
// JavaScript built-in types
console.log('util.types.isDate(new Date()):',
util.types.isDate(new Date()));
console.log('util.types.isRegExp(/test/):',
util.types.isRegExp(/test/));
console.log('util.types.isPromise(Promise.resolve()):',
util.types.isPromise(Promise.resolve()));
// Node.js-specific types
console.log('util.types.isArrayBuffer(new ArrayBuffer(0)):',
util.types.isArrayBuffer(new ArrayBuffer(0)));
console.log('util.types.isSharedArrayBuffer(new SharedArrayBuffer(0)):',
util.types.isSharedArrayBuffer(new SharedArrayBuffer(0)));
console.log('util.types.isUint8Array(new Uint8Array()):',
util.types.isUint8Array(new Uint8Array()));
// More advanced types
console.log('util.types.isProxy(new Proxy({}, {})):',
util.types.isProxy(new Proxy({}, {})));
console.log('util.types.isExternal(Requiring C++ binding):',
'Not demonstrated in this example');
পরিত্যক্ত আবেদন
Node.js API .
পরিত্যাগের কৌশল:
util.deprecate(fn, msg[, code])
নির্দেশ করে যে একটি ফাংশন বাতিল করা হয়েছে এবং এটিকে কল করা হলে একটি সতর্কতা নির্গত হয়।
const util = require('util');
// Original function
function oldFunction(x, y) {
return x + y;
}
// Deprecate the function
const deprecatedFunction = util.deprecate(
oldFunction,
'oldFunction() is deprecated. Use newFunction() instead.',
'DEP0001'
);
// New function
function newFunction(x, y) {
return x + y;
}
// Using the deprecated function will show a warning
console.log('Result:', deprecatedFunction(5, 10));
// Using the new function
console.log('Result:', newFunction(5, 10));
ড্রপআউট সতর্কতা পরিচালনা করুন
আপনি পরিবেশ ভেরিয়েবল ব্যবহার করে ড্রপআউট সতর্কতা প্রদর্শন নিয়ন্ত্রণ করতে পারেন:
# Show all deprecation warnings
NODE_OPTIONS='--trace-deprecation'
# Show only the first occurrence of each deprecation
NODE_OPTIONS='--no-deprecation'
# Silence all deprecation warnings
NODE_OPTIONS='--no-warnings'
# Turn deprecation warnings into exceptions
NODE_OPTIONS='--throw-deprecation'
ডিবাগিং এবং ডেভেলপমেন্ট অ্যাপ্লিকেশন
Node.js , .
util.debuglog(section)
একটি ফাংশন তৈরি করে যা শর্তসাপেক্ষে NODE_DEBUG এনভায়রনমেন্ট ভেরিয়েবলের উপর ভিত্তি করে stderr-এ ডিবাগ বার্তা লেখে।
এটি সম্পূর্ণ বৈশিষ্ট্যযুক্ত রেকর্ডিং লাইব্রেরির একটি হালকা বিকল্প।
ডিবাগ লগিংয়ের জন্য সর্বোত্তম অনুশীলন:
উদাহরণ ব্যবহার:
// Enable debug logging for specific modules
// NODE_DEBUG=app,db node your-app.js
// In your application
const debugApp = util.debuglog('app');
const debugDB = util.debuglog('db');
// These will only log when 'app' is in NODE_DEBUG
debugApp('Application started with config: %j', config);
// These will only log when 'db' is in NODE_DEBUG
debugDB('Connected to database: %s', connectionString);
// Enable all debug logs (not recommended in production)
// NODE_DEBUG=* node your-app.js
const util = require('util');
// Create debug loggers for different sections
const debugApp = util.debuglog('app');
const debugDB = util.debuglog('db');
const debugAuth = util.debuglog('auth');
// These messages only appear when NODE_DEBUG includes 'app'
debugApp('Application starting...');
debugApp('Configuration loaded from %j', { source: 'config.json' });
// These messages only appear when NODE_DEBUG includes 'db'
debugDB('Connected to database');
debugDB('Query executed: %s', 'SELECT * FROM users');
// These messages only appear when NODE_DEBUG includes 'auth'
debugAuth('User authenticated: %s', 'john.doe');
// To see these messages, run your app with:
// NODE_DEBUG=app,db node your-app.js
console.log('Application running normally (this always shows)');
সারাংশ
Node.js Util Node.js :
স্ট্রিং বিন্যাস
util.format()
উপাদান বিশ্লেষণ
util.inspect()
অ্যাসিঙ্ক পরিবর্তন
util.promisify() util.callbackify()
টাইপ টেস্ট
util.types
পরিত্যাগ ব্যবস্থাপনা
util.deprecate()
ডিবাগ লগ
util.debuglog()
এই অ্যাপ্লিকেশনগুলি বোঝার এবং ব্যবহার করে, আপনি অত্যন্ত রক্ষণাবেক্ষণযোগ্য, ডিবাগযোগ্য এবং কার্যকরী Node.js অ্যাপ্লিকেশন লিখতে পারেন।