Safely convert req.path into a local file path.
- Consistent handling of
/fooand/foo/ - Resolves
/footo/foo.htmlor/foo/index.html - Checks if the resolved file exists
- Supports custom file extensions (e.g.,
.html) - Protects against path traversal
npm install @ryanburnette/url-path-to-local-pathimport 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');- `directory` (required): The directory to resolve paths within.
- `extension` (required): The file extension to resolve, e.g., `.html`.
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();
}
}