Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ryanburnette/url-path-to-local-path
Safely convert req.path into a local path.
https://github.com/ryanburnette/url-path-to-local-path
Last synced: 22 days ago
JSON representation
Safely convert req.path into a local path.
- Host: GitHub
- URL: https://github.com/ryanburnette/url-path-to-local-path
- Owner: ryanburnette
- License: isc
- Created: 2020-05-14T20:51:40.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2020-05-15T13:27:08.000Z (over 4 years ago)
- Last Synced: 2024-04-24T18:09:04.978Z (10 months ago)
- Language: JavaScript
- Homepage:
- Size: 8.79 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# 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
```bash
npm install @ryanburnette/url-path-to-local-path
```## Usage
```javascript
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
```javascript
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();
}
}
```