5.1.0 • Published 1 year ago

@ryanburnette/url-path-to-local-path v5.1.0

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

url-path-to-local-path

Safely convert req.path into a local file path.

Features

  • Consistent handling of /foo and /foo/
  • Resolves /foo to /foo.html or /foo/index.html
  • Checks if the resolved file exists
  • Supports custom file extensions (e.g., .html)
  • Protects against path traversal

Installation

npm install @ryanburnette/url-path-to-local-path

Usage

import UrlPathToLocalPath from '@ryanburnette/url-path-to-local-path';
import fs from 'fs/promises';

const resolvePath = UrlPathToLocalPath.create({
  directory: './content',
  extension: '.html'
});

// Example: Resolving a path and reading the file
const localPath = await resolvePath('/foo');
const content = await fs.readFile(localPath, 'utf8');

API

`UrlPathToLocalPath.create(options)`

  • `directory` (required): The directory to resolve paths within.
  • `extension` (required): The file extension to resolve, e.g., `.html`.

Example with Express

import UrlPathToLocalPath from '@ryanburnette/url-path-to-local-path';
import fs from 'fs/promises';

const resolvePath = UrlPathToLocalPath.create({
  directory: './content',
  extension: '.html'
});

export default async function (req, res, next) {
  try {
    const localPath = await resolvePath(req.path);
    const content = await fs.readFile(localPath, 'utf8');
    res.send(content);
  } catch (err) {
    next();
  }
}
5.1.0

1 year ago

5.0.0

1 year ago

4.0.0

1 year ago

3.0.0

6 years ago

2.0.2

6 years ago

2.0.1

6 years ago

2.0.0

6 years ago

1.4.1

7 years ago

1.4.0

7 years ago

1.3.2

7 years ago

1.3.1

7 years ago

1.3.0

7 years ago

1.2.0

7 years ago

1.1.0

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago