Node.js Path Module

Node.js

पथ मॉड्यूल क्या है?

पाथ मॉड्यूल Node.js का एक अंतर्निहित मॉड्यूल है जो विभिन्न ऑपरेटिंग मोड में फ़ाइल पथों में हेरफेर करने और बदलने के लिए उपकरण प्रदान करता है।

चूँकि विंडोज़ ट्रेलिंग स्लैश (\) का उपयोग करता है और POSIX सिस्टम (लिनक्स, MacOS) ट्रेलिंग स्लैश (/) का उपयोग करता है, पाथ मॉड्यूल आपको क्रॉस-प्लेटफ़ॉर्म कोड लिखने में सक्षम बनाता है जो किसी भी सिस्टम पर सही ढंग से काम करता है।

क्रॉस-प्लेटफ़ॉर्म पथ प्रबंधन

सभी ऑपरेटिंग मोड पर काम करता है

पथ हेरफेर और सामान्यीकरण

मार्ग बदलना और समायोजित करना

फ़ाइल एक्सटेंशन निष्कर्षण

फ़ाइल प्रकारों की आसान पहचान

पथ मॉड्यूल का उपयोग करना

पाथ मॉड्यूल Node.js में एक महत्वपूर्ण मॉड्यूल है, इसलिए किसी इंस्टॉलेशन की आवश्यकता नहीं है।

आप CommonJS या ES मॉड्यूल व्याकरण का उपयोग कर सकते हैं और इसे आयात कर सकते हैं:

CommonJS (Node.js में डिफ़ॉल्ट)

const path = require('path');

// Destructure specific methods if needed
const { join, resolve, basename } = require('path');

ES Modules (Node.js 14+ with "type": "module" in package.json)

import path from 'path';

// Or import specific methods
import { join, resolve, basename } from 'path';

💡सर्वश्रेष्ठ प्रणालियां:

ईएस मॉड्यूल का उपयोग करते समय बेहतर ट्री-शेकिंग और छोटे पैकेज आकार के लिए, केवल उन तरीकों को आयात करें जिनकी आपको आवश्यकता है।

पथ मॉड्यूल विधियाँ

path.basename()

यूनिक्स बेसनेम कमांड के समतुल्य, पथ का अंतिम भाग लौटाता है।

const path = require('path');

// Get filename from a path
const filename = path.basename('/users/docs/file.txt');
console.log(filename); // 'file.txt'

// Get filename without extension
const filenameWithoutExt = path.basename('/users/docs/file.txt', '.txt');
console.log(filenameWithoutExt); // 'file'

__dirname और __फ़ाइलनाम

Node.js , __dirname __filename CommonJS , .

उदाहरण: CommonJS में __dirname और __filename का उपयोग करना

// CommonJS module (e.g., app.js)
const path = require('path');

// Get the directory name of the current module
console.log('Directory name:', __dirname);

// Get the file name of the current module
console.log('File name:', __filename);

// Building paths relative to the current module
const configPath = path.join(__dirname, 'config', 'app-config.json');
console.log('Config file path:', configPath);

// Getting the directory name using path.dirname()
console.log('Directory using path.dirname():', path.dirname(__filename));

उदाहरण: ईएस मॉड्यूल में __dirname और __filename प्राप्त करना

// ES Module (e.g., app.mjs or "type": "module" in package.json)
import { fileURLToPath } from 'url';
import { dirname } from 'path';

// Get the current module's URL
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

console.log('ES Module file path:', __filename);
console.log('ES Module directory:', __dirname);

// Example with dynamic imports
async function loadConfig() {
  const configPath = new URL('../config/app-config.json', import.meta.url);
  const config = await import(configPath, { with: { type: 'json' } });
  return config;
}

🔧सर्वोत्तम प्रथाएं:

  • CommonJS मॉड्यूल में फ़ाइल पथ बनाने के लिए path.join() या path.resolve() के साथ __dirname का उपयोग करें
  • ईएस मॉड्यूल के लिए, समकक्ष कार्यक्षमता प्राप्त करने के लिए fileURLToPath और dirname के साथ आयात.मेटा.url का उपयोग करें
  • path.join() __dirname ,

path.extname()

पथ का विस्तार लौटाता है। चरित्र की अंतिम घटना से लेकर स्ट्रिंग के अंत तक।

const path = require('path');

const extension = path.extname('file.txt');
console.log(extension); // '.txt'

console.log(path.extname('index.html')); // '.html'
console.log(path.extname('index.coffee.md')); // '.md'
console.log(path.extname('index.')); // '.'
console.log(path.extname('index')); // ''
console.log(path.extname('.index')); // ''

path.join()

प्लेटफ़ॉर्म-विशिष्ट विभाजक का उपयोग करके सभी दिए गए पथ खंडों को एक विभाजक में संयोजित करता है, फिर परिणामी पथ को सामान्य करता है।

उदाहरण: मूल पथ युग्मन

const path = require('path');

// Join path segments
const fullPath = path.join('/users', 'docs', 'file.txt');
console.log(fullPath); // Output depends on OS

// Handle relative paths and navigation
console.log(path.join('/users', '../system', './logs', 'file.txt'));

// Handle multiple slashes
console.log(path.join('users', '//docs', 'file.txt')); // Normalizes slashes

💡नोट:

path.join() को + के साथ स्ट्रिंग संयोजन पर प्राथमिकता दी जाती है क्योंकि यह विभिन्न ऑपरेटिंग मोड में विभिन्न पथ विभाजकों को संभालता है।

path.resolve()

पथों या पथ भागों के अनुक्रम को एक पूर्ण पथ में हल करता है, पूर्ण पथ बनने तक दाएं से बाएं तक प्रसंस्करण करता है।

उदाहरण: समाधान पथ

const path = require('path');

// 1. Resolve relative to current working directory
console.log(path.resolve('file.txt'));

// 2. Resolve with multiple segments
console.log(path.resolve('/users', 'docs', 'file.txt'));

// 3. Right-to-left processing
console.log(path.resolve('/first', '/second', 'third')); // '/second/third'

// 4. Using __dirname for module-relative paths
console.log(path.resolve(__dirname, 'config', 'app.json'));

🌟सहायता नोट:

वर्तमान मॉड्यूल के स्थान के सापेक्ष पूर्ण पथ उत्पन्न करने के लिए path.resolve() का उपयोग आमतौर पर __dirname के साथ किया जाता है।

path.parse()

उन गुणों के साथ एक ऑब्जेक्ट लौटाता है जो पथ के महत्वपूर्ण घटकों का प्रतिनिधित्व करते हैं।

उदाहरण: फ़ाइल पथ को पार्स करना

const path = require('path');

// Parse a file path
const pathInfo = path.parse('/users/docs/file.txt');
console.log(pathInfo);
/* Output on Unix/macOS:
{
  root: '/',
  dir: '/users/docs',
  base: 'file.txt',
  ext: '.txt',
  name: 'file'
}
*/

// Accessing parsed components
console.log('Directory:', pathInfo.dir); // /users/docs
console.log('Filename:', pathInfo.base); // file.txt
console.log('Name only:', pathInfo.name); // file
console.log('Extension:', pathInfo.ext); // .txt

ℹ️नोट:

path.parse() path.format() .

path.format()

किसी ऑब्जेक्ट से पथ स्ट्रिंग लौटाता है, जो path.parse() के विपरीत है।

उदाहरण: रूट ऑब्जेक्ट डिज़ाइन करना

const path = require('path');

// Method 1: Using dir and base
const pathString1 = path.format({
  dir: '/users/docs',
  base: 'file.txt'
});
console.log(pathString1); // '/users/docs/file.txt'

// Method 2: Using root, dir, name, and ext
const pathString2 = path.format({
  root: '/',
  dir: '/users/docs',
  name: 'file',
  ext: '.txt'
});
console.log(pathString2); // '/users/docs/file.txt'

// Practical example: Modify and reconstruct a path
const parsedPath = path.parse('/users/docs/old-file.txt');
parsedPath.base = 'new-file.md';
const newPath = path.format(parsedPath);
console.log(newPath); // '/users/docs/new-file.md'

💡नोट:

path.format() , dir root , root .

path.normalize()

दिए गए पथ को सामान्य बनाता है, .. और। भागों को क्रमबद्ध करना और अनावश्यक विभाजकों को हटाना।

उदाहरण: पथों को सामान्य बनाना

const path = require('path');

// Resolve relative navigation
console.log(path.normalize('/users/./docs/../data/file.txt')); // '/users/data/file.txt'

// Handle multiple consecutive slashes
console.log(path.normalize('/users//docs////file.txt')); // '/users/docs/file.txt'

// Windows-style paths (automatically handled)
console.log(path.normalize('C:\\users\\docs\\..\\file.txt')); // 'C:\\users\\file.txt'

// Edge cases
console.log(path.normalize('')); // '.'
console.log(path.normalize('.')); // '.'
console.log(path.normalize('..')); // '..'
console.log(path.normalize('/..')); // '/'

🔒सुरक्षा नोट:

path.normalize() .. , . .

path.relative()

पहले पथ से दूसरे पथ पर सापेक्ष पथ लौटाता है, या यदि पथ समान हैं तो एक खाली स्ट्रिंग लौटाता है।

उदाहरण: सापेक्ष पथ ढूँढना

const path = require('path');

// Basic relative path
console.log(path.relative('/users/docs/file.txt', '/users/images/photo.jpg'));
// Output: '../../images/photo.jpg'

// Same directory
console.log(path.relative('/users/docs/file1.txt', '/users/docs/file2.txt'));
// Output: 'file2.txt'

// Same file
console.log(path.relative('/users/docs/file.txt', '/users/docs/file.txt'));
// Output: ''

// Different roots (Windows)
console.log(path.relative('C:\\user\\test\\aaa', 'C:\\user\\impl\\bbb'));
// Output: '..\\..\\impl\\bbb'

// Practical example: Creating a relative path for web
const absolutePath = '/var/www/static/images/logo.png';
const webRoot = '/var/www/';
const webPath = path.relative(webRoot, absolutePath).replace(/\\/g, '/');
console.log(webPath); // 'static/images/logo.png'

🌟सहायता नोट:

path.relative() विशेष रूप से तब उपयोगी होता है जब आपको अपने प्रोजेक्ट में विभिन्न स्थानों के बीच सापेक्ष URL या पोर्टेबल पथ बनाने की आवश्यकता होती है।

path.isAbsolute()

यह निर्धारित करता है कि दिया गया पथ एक निरपेक्ष पथ है या नहीं। कार्यशील निर्देशिका की परवाह किए बिना, एक निरपेक्ष पथ हमेशा एक ही स्थान पर समाप्त होता है।

उदाहरण: निरपेक्ष पथों की जाँच करना

const path = require('path');

// POSIX (Unix/Linux/macOS)
console.log(path.isAbsolute('/users/docs')); // true
console.log(path.isAbsolute('users/docs')); // false

// Windows
console.log(path.isAbsolute('C:\\temp')); // true
console.log(path.isAbsolute('temp')); // false

// UNC paths (Windows network paths)
console.log(path.isAbsolute('\\\\server\\share')); // true

// Practical example: Ensure absolute path for config files
function ensureAbsolute(configPath) {
  return path.isAbsolute(configPath)
    ? configPath
    : path.resolve(process.cwd(), configPath);
}

console.log(ensureAbsolute('config.json')); // Resolves to absolute path
console.log(ensureAbsolute('/etc/app/config.json')); // Already absolute

ℹ️नोट:

विंडोज़ पर, कोलन (जैसे 'C:\\') से शुरू होने वाले पथ और उसके बाद प्रवाह वर्ण को निरपेक्ष माना जाता है, जैसे कि UNC पथ (जैसे कि '\\\\server\\share') को पूर्ण माना जाता है।

पथ गुण

path.sep

एक प्लेटफ़ॉर्म-विशिष्ट पथ खंड विभाजक प्रदान करता है।

यह एक चरण-मात्र विशेषता है जो वर्तमान ऑपरेटिंग मोड के लिए डिफ़ॉल्ट पथ खंड विभाजक प्रदान करती है।

उदाहरण: पथ विभाजकों के साथ कार्य करना

const path = require('path');

// Get the platform-specific separator
console.log(`Path separator: ${JSON.stringify(path.sep)}`); // '\\' on Windows, '/' on POSIX

// Building paths safely across platforms
const parts = ['users', 'docs', 'file.txt'];
const filePath = parts.join(path.sep);
console.log('Built path:', filePath);

// Splitting paths correctly
const pathToSplit = process.platform === 'win32'
  ? 'C:\\Users\\docs\\file.txt'
  : '/users/docs/file.txt';
const pathParts = pathToSplit.split(path.sep);
console.log('Split path:', pathParts);

// Normalizing paths with the correct separator
const normalized = path.normalize(`users${path.sep}docs${path.sep}..${path.sep}file.txt`);
console.log('Normalized path:', normalized);

💡सर्वश्रेष्ठ प्रणालियां:

अपने Node.js अनुप्रयोगों में क्रॉस-प्लेटफ़ॉर्म संगतता सुनिश्चित करने के लिए हार्ड-कोडित पथ विभाजकों के बजाय हमेशा path.sep का उपयोग करें।

path.delimiter

एक प्लेटफ़ॉर्म-विशिष्ट पथ विभाजक प्रदान करता है जिसका उपयोग PATH जैसे पर्यावरण चर में पथों को अलग करने के लिए किया जाता है।

उदाहरण: PATH पर्यावरण चर के साथ कार्य करना

const path = require('path');

// Get the platform-specific delimiter
console.log(`Path delimiter: ${JSON.stringify(path.delimiter)}`); // ';' on Windows, ':' on POSIX

// Working with PATH environment variable
function findInPath(executable) {
  if (!process.env.PATH) return null;

  // Split PATH into directories
  const pathDirs = process.env.PATH.split(path.delimiter);

  // Check each directory for the executable
  for (const dir of pathDirs) {
    try {
      const fullPath = path.join(dir, executable);
      require('fs').accessSync(fullPath, require('fs').constants.X_OK);
      return fullPath;
    } catch (err) {
      // File not found or not executable
      continue;
    }
  }
  return null;
}

// Example: Find node executable in PATH
const nodePath = findInPath(process.platform === 'win32' ? 'node.exe' : 'node');
console.log('Node.js path:', nodePath || 'Not found in PATH');

ℹ️नोट:

path.delimiter PATH NODE_PATH .

path.win32

विंडोज़-विशिष्ट पथ विधियों तक पहुंच प्रदान करता है, जिससे आप चाहे जो भी ऑपरेटिंग सिस्टम चला रहे हों, आपको विंडोज़-शैली पथों के साथ काम करने की अनुमति मिलती है।

उदाहरण: किसी भी प्लेटफ़ॉर्म पर विंडोज़ पथ के साथ कार्य करना

const path = require('path');

// Always use Windows-style path handling
const winPath = 'C:\\Users\\user\\Documents\\file.txt';
console.log('Windows basename:', path.win32.basename(winPath));
console.log('Windows dirname:', path.win32.dirname(winPath));

// Normalize Windows paths
console.log('Normalized path:', path.win32.normalize('C:\\\\temp\\\\foo\\..\\bar\\file.txt'));

// Convert between forward and backward slashes
const mixedPath = 'C:/Users/User/Documents//file.txt';
console.log('Normalized mixed slashes:', path.win32.normalize(mixedPath));

// Working with UNC paths
const uncPath = '\\\\server\\share\\folder\\file.txt';
console.log('UNC path components:', path.win32.parse(uncPath));

🖥️उदाहरण:

Path.win32 ऑब्जेक्ट विशेष रूप से तब उपयोगी होता है जब आपके एप्लिकेशन को विंडोज़ सिस्टम रजिस्ट्री या कॉन्फ़िगरेशन फ़ाइल से पथ संसाधित करते समय विंडोज़-शैली पथों के साथ गैर-विंडोज़ प्लेटफ़ॉर्म पर काम करने की आवश्यकता होती है।

path.posix

सभी प्लेटफार्मों पर लगातार प्रथम-स्लैश पथ प्रबंधन सुनिश्चित करते हुए, POSIX-संगत पथ विधियों तक पहुंच प्रदान करता है।

उदाहरण: किसी भी प्लेटफ़ॉर्म पर POSIX पथों के साथ कार्य करना

const path = require('path');

// Always use POSIX-style path handling
const posixPath = '/home/user/documents/file.txt';
console.log('POSIX basename:', path.posix.basename(posixPath));
console.log('POSIX dirname:', path.posix.dirname(posixPath));

// Normalize POSIX paths
console.log('Normalized path:', path.posix.normalize('/usr/local//bin/../lib/file.txt'));

// Working with relative paths
console.log('Relative path:', path.posix.relative('/data/test/aaa', '/data/impl/bbb'));

// Joining paths with POSIX separators
const urlPath = ['static', 'images', 'logo.png'].join(path.posix.sep);
console.log('URL path:', urlPath); // 'static/images/logo.png'

🌐उदाहरण:

वेब एप्लिकेशन, कॉन्फ़िगरेशन फ़ाइलों या एपीआई के साथ काम करते समय path.posix ऑब्जेक्ट विशेष रूप से उपयोगी होता है, जो अंतर्निहित ऑपरेटिंग सिस्टम की परवाह किए बिना, लगातार पथ प्रबंधन सुनिश्चित करने के लिए POSIX-शैली पथ की अपेक्षा करता है।

सामान्य उपयोग के मामले और सर्वोत्तम प्रथाएँ

ब्लॉक पथों के साथ कार्य करना

मॉड्यूल पथों को समझना और उनके साथ काम करना रखरखाव योग्य Node.js अनुप्रयोगों के निर्माण के लिए महत्वपूर्ण है। वास्तविक दुनिया की स्थितियों में मार्ग हेरफेर के लिए यहां कुछ सामान्य पैटर्न और सर्वोत्तम अभ्यास दिए गए हैं।

उदाहरण: ब्लॉक पथ निर्धारण

const path = require('path');
const fs = require('fs/promises');

// Current module's directory and file info
console.log('Module directory:', __dirname);
console.log('Module file path:', __filename);

// Common path patterns
const paths = {
  // Configuration files relative to project root
  config: path.join(__dirname, '..', 'config', 'app.json'),
 
  // Logs directory (create if doesn't exist)
  logs: path.join(__dirname, '..', 'logs'),
 
  // Public assets
  public: path.join(__dirname, '..', 'public'),
 
  // Uploads directory with proper permissions
  uploads: path.join(__dirname, '..', 'uploads')
};

// Ensure directories exist
async function ensureDirectories() {
  try {
    await Promise.all([
      fs.mkdir(paths.logs, { recursive: true }),
      fs.mkdir(paths.public, { recursive: true }),
      fs.mkdir(paths.uploads, { recursive: true, mode: 0o755 })
    ]);
    console.log('All directories ready');
  } catch (error) {
    console.error('Error creating directories:', error);
  }
}

// Example: Load configuration
async function loadConfig() {
  try {
    const configData = await fs.readFile(paths.config, 'utf8');
    return JSON.parse(configData);
  } catch (error) {
    console.error('Error loading config:', error.message);
    return {};
  }
}

// Example: Log to application log
async function logToFile(message) {
  try {
    const logFile = path.join(paths.logs, `${new Date().toISOString().split('T')[0]}.log`);
    const logMessage = `[${new Date().toISOString()}] ${message}\n`;
    await fs.appendFile(logFile, logMessage, 'utf8');
  } catch (error) {
    console.error('Error writing to log:', error);
  }
}

// Initialize and run examples
(async () => {
  await ensureDirectories();
  const config = await loadConfig();
  console.log('Loaded config:', config);
  await logToFile('Application started');
})();

ईएस मॉड्यूल रूट हैंडलिंग

ECMAScript मॉड्यूल में (.mjs एक्सटेंशन वाली फ़ाइलें या यदि "type": "module" package.json में सेट है), __dirname और __filename उपलब्ध नहीं हैं। यहां ES मॉड्यूल में पथों को संभालने का तरीका बताया गया है:

// ES Module (app.mjs or with "type": "module" in package.json)
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { promises as fs } from 'fs';

// Get current module's directory and file path
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Utility function for path resolution in ES modules
function resolvePath(relativePath) {
  return new URL(relativePath, import.meta.url).pathname;
}

// Example usage
const configPath = join(__dirname, '..', 'config', 'settings.json');
const assetPath = resolvePath('../assets/logo.png');

// Dynamic imports with paths relative to current module
async function loadModule(modulePath) {
  const fullPath = new URL(modulePath, import.meta.url);
  return import(fullPath);
}

🔑महत्वपूर्ण बिंदु:

  • वर्तमान मॉड्यूल का URL प्राप्त करने के लिए आयात.मेटा.url का उपयोग करें
  • आवश्यकता पड़ने पर फ़ाइल URLToPath() के साथ फ़ाइल पथ में URL बदलें
  • मूल रूप से आयात.मेटा.यूआरएल के साथ यूआरएल कंस्ट्रक्टर का उपयोग करें
  • क्रॉस-प्लेटफ़ॉर्म संगतता के लिए path.join() और अन्य पथ विधियों का उपयोग जारी रखें

उन्नत पथ हेरफेर पैटर्न

वास्तविक दुनिया के अनुप्रयोगों में पथों के साथ काम करने के लिए यहां कुछ उन्नत पैटर्न दिए गए हैं।

उदाहरण: उत्पादन अनुप्रयोगों के लिए अनुप्रयोगों को रूट करें

const path = require('path');
const fs = require('fs/promises');
const os = require('os');

// Path utility class
class PathUtils {
  static get tempDir() {
    return path.join(os.tmpdir(), 'myapp');
  }
 
  static get userHome() {
    return process.env.HOME || process.env.USERPROFILE || os.homedir();
  }

  static async ensureDirectory(dirPath) {
    try {
      await fs.mkdir(dirPath, { recursive: true, mode: 0o755 });
      return true;
    } catch (error) {
      if (error.code !== 'EEXIST') throw error;
      return false;
    }
  }
 
  static isSafePath(baseDir, targetPath) {
    const normalizedBase = path.resolve(baseDir);
    const normalizedTarget = path.resolve(targetPath);
    return normalizedTarget.startsWith(normalizedBase);
  }
 
  static getUniqueFilename(dir, filename) {
    const { name, ext } = path.parse(filename);
    let counter = 1;
    let candidate = filename;
   
    while (fs.existsSync(path.join(dir, candidate))) {
      candidate = `${name} (${counter++})${ext}`;
    }
    return candidate;
  }
}

// Example usage
(async () => {
  // Ensure temp directory exists
  await PathUtils.ensureDirectory(PathUtils.tempDir);
 
  // Safe file operations
  const userUploads = path.join(PathUtils.userHome, 'uploads');
  const safePath = path.join(userUploads, 'profile.jpg');
 
  if (PathUtils.isSafePath(userUploads, safePath)) {
    console.log('Path is safe for operations');
  } else {
    console.error('Potential path traversal attack detected!');
  }
 
  // Generate unique filename
  const uniqueName = PathUtils.getUniqueFilename(
    userUploads,
    'document.pdf'
  );
  console.log('Unique filename:', uniqueName);
 
  // Working with file extensions
  const filePath = '/users/john/docs/report.pdf';
  const fileInfo = {
    name: path.basename(filePath, path.extname(filePath)),
    ext: path.extname(filePath),
    dir: path.dirname(filePath)
  };
  console.log('File info:', fileInfo);
})();

सुरक्षा संबंधी विचार

फ़ाइल पथों के साथ काम करते समय सुरक्षा हमेशा सर्वोच्च प्राथमिकता होनी चाहिए। यहां कुछ महत्वपूर्ण सुरक्षा विचार और सर्वोत्तम प्रथाएं दी गई हैं:

उदाहरण: सुरक्षित पथ संचालन

const path = require('path');
const fs = require('fs').promises;

// 1. Prevent directory traversal attacks
function safeJoin(base, ...paths) {
  const targetPath = path.join(base, ...paths);
  const normalizedPath = path.normalize(targetPath);
 
  // Ensure the resulting path is still within the base directory
  if (!normalizedPath.startsWith(path.resolve(base))) {
    throw new Error('Access denied: Path traversal detected');
  }
 
  return normalizedPath;
}

// 2. Validate file extensions
const ALLOWED_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif']);

function hasValidExtension(filePath) {
  const ext = path.extname(filePath).toLowerCase();
  return ALLOWED_EXTENSIONS.has(ext);
}

// 3. Safe file operations
async function safeReadFile(baseDir, relativePath) {
  const safePath = safeJoin(baseDir, relativePath);
 
  // Additional security checks
  if (!hasValidExtension(safePath)) {
    throw new Error('Invalid file type');
  }
 
  const stats = await fs.stat(safePath);
  if (!stats.isFile()) {
    throw new Error('Not a file');
  }
 
  return fs.readFile(safePath, 'utf8');
}

// Example usage
(async () => {
  const UPLOAD_DIR = path.join(process.cwd(), 'uploads');
  const userInput = '../../../etc/passwd'; // Malicious input
 
  try {
    // This will throw an error due to path traversal attempt
    const content = await safeReadFile(UPLOAD_DIR, userInput);
    console.log('File content:', content);
  } catch (error) {
    console.error('Security error:', error.message);
  }
})();

🔒सुरक्षा सर्वोत्तम प्रथाएँ:

  • उपयोगकर्ता द्वारा प्रदत्त मार्गों को हमेशा जांचें और परिष्कृत करें
  • डायरेक्टरी ट्रैवर्सल को रोकने के लिए path.normalize() का उपयोग करें
  • मान्य फ़ाइल प्रकार सत्यापन सक्षम करें
  • उपयुक्त फ़ाइल अनुमतियाँ सेट करें
  • न्यूनतम प्रस्ताव नीति का प्रयोग करें
  • एस्लिंट-प्लगइन-सिक्योरिटी जैसे सुरक्षा लिंटर का उपयोग करें

क्रॉस-प्लेटफ़ॉर्म विकास

क्रॉस-प्लेटफ़ॉर्म एप्लिकेशन विकसित करते समय, विभिन्न ऑपरेटिंग मोड के बीच पथ अंतर को ठीक से संभालना महत्वपूर्ण है।

उदाहरण: क्रॉस-प्लेटफ़ॉर्म पथ हेरफेर

const path = require('path');

// Platform detection
const isWindows = process.platform === 'win32';
const isMac = process.platform === 'darwin';
const isLinux = process.platform === 'linux';

// Platform-specific paths
const appDataDir = isWindows
  ? path.join(process.env.APPDATA || path.join(process.env.USERPROFILE, 'AppData', 'Roaming'))
  : path.join(process.env.HOME || process.env.USERPROFILE, isMac ? 'Library/Application Support' : '.config');

// Application-specific directories
const appName = 'MyApp';
const appDir = path.join(appDataDir, appName);

// Ensure application directory exists
require('fs').mkdirSync(appDir, { recursive: true });

// Platform-specific temporary directory
const tempDir = path.join(require('os').tmpdir(), appName);

// Example: Platform-agnostic path handling
function getConfigPath() {
  const configName = 'config.json';

  // Development vs production paths
  if (process.env.NODE_ENV === 'development') {
    return path.join(process.cwd(), 'config', configName);
  }
  
  // Production path
  return path.join(appDir, configName);
}

console.log('Application directory:', appDir);
console.log('Temporary directory:', tempDir);
console.log('Config file path:', getConfigPath());

🌍क्रॉस-प्लेटफ़ॉर्म हेल्पनोट्स:

  • स्ट्रिंग संयोजन के बजाय हमेशा path.join() का उपयोग करें
  • जब प्लेटफ़ॉर्म-विशिष्ट विभाजक की आवश्यकता हो तो path.sep का उपयोग करें
  • केस-संवेदी अंतरों को संभालें (विंडोज़ केस-संवेदी नहीं है)
  • विभिन्न प्लेटफार्मों पर ट्रैक की लंबाई की सीमाओं के बारे में जानें
  • सभी लक्षित प्लेटफ़ॉर्म पर अपने ऐप का परीक्षण करें

सारांश

Node.js Path - .

यह एप्लिकेशन का एक समृद्ध सेट प्रदान करता है जो मदद करता है:

फ़ाइल पथों को पार्स और प्रारूपित करें
पथों को सामान्य बनाना और उनका समाधान करना
सापेक्ष और निरपेक्ष पथों के साथ कार्य करना
पथ तत्वों में हेरफेर करना
क्रॉस-प्लेटफ़ॉर्म कोड लिखना जो किसी भी ऑपरेटिंग सिस्टम पर पूरी तरह से काम करता है

पाथ मॉड्यूल का उपयोग करके, आप अधिक मजबूत और पोर्टेबल कोड लिख सकते हैं जो विभिन्न वातावरणों में फ़ाइल पथों को सही ढंग से संभालता है।

अभ्यास

फ़ाइल और निर्देशिका पथों के साथ काम करने के लिए उपयोगिताएँ प्रदान करने के लिए सही मॉड्यूल नाम खींचें और छोड़ें।

The ______ module.

path
✓ ठीक है! पथ मॉड्यूल फ़ाइल और निर्देशिका पथों के साथ काम करने के लिए उपयोगिताएँ प्रदान करता है।
fs
✗ ग़लत! एफएस मॉड्यूल फ़ाइल प्रारूप संचालन के लिए है, लेकिन पथ हेरफेर के लिए नहीं।
os
✗ ग़लत! ओएस मॉड्यूल ऑपरेटिंग सिस्टम से संबंधित कार्यों के लिए है, पथ हेरफेर के लिए नहीं।
url
✗ ग़लत! यूआरएल मॉड्यूल यूआरएल को संभालने के लिए है, फ़ाइल पथों के लिए नहीं।