Node Scripting Patterns
Path Segment Parse
Node scripts often split path-like strings into directory, base name, and extension pieces.
Path Segment Parse
path_parts.ts
type PathParts = {
directory: string;
base: string;
extension: string;
};
function splitPath(path: string): PathParts {
const segments: string[] = path.split("/");
const file: string = segments[segments.length - 1];
const dot: number = file.lastIndexOf(".");
return {
directory: segments.slice(0, -1).join("/"),
base: file.slice(0, dot),
extension: file.slice(dot + 1)
};
}
const fileName: string = ;
const parts: PathParts = splitPath(`data/${fileName}`);
console.log(`${parts.directory}:${parts.base}:${parts.extension}`);
type PathParts = {
directory: string;
base: string;
extension: string;
};
function splitPath(path: string): PathParts {
const segments: string[] = path.split("/");
const file: string = segments[segments.length - 1];
const dot: number = file.lastIndexOf(".");
return {
directory: segments.slice(0, -1).join("/"),
base: file.slice(0, dot),
extension: file.slice(dot + 1)
};
}
const fileName: string = ;
const parts: PathParts = splitPath(`data/${fileName}`);
console.log(`${parts.directory}:${parts.base}:${parts.extension}`);
path parts
Separating path parts lets script code route files by name or extension without changing the real filesystem.