Skip to main content

Command Palette

Search for a command to run...

L4. Path Module in Node.js

Updated
โ€ข1 min readโ€ขView as Markdown

1. Importing Path Module

console.log("Path Module");  
import path from 'path';
  • path is a built-in module in Node.js.

  • Helps handle and transform file paths easily.

2. Joining Paths

const fullPath = path.join('/path', 's.txt', 's.json');  
console.log(fullPath);
  • path.join(): Merges multiple path segments into a single path.

3. Resolving the Current Working Directory

const resolvedPath = path.resolve();
console.log(resolvedPath);
  • path.resolve(): Returns the absolute path of the current working directory.

4. Getting File Extension

const ext = path.extname('file.txt');  
console.log(ext); // Output: .txt
  • path.extname(): Extracts the file extension.

5. Security Consideration

  • Paths can be restricted in APIs to prevent unauthorized file access.

  • Helps avoid directory traversal attacks.

More from this blog

N

Nodejs

12 posts