File Paths in TypeScript
Here’s the translation of the Go code example to TypeScript, along with explanations in Markdown format suitable for Hugo:
The path
module in Node.js provides functions to parse and construct file paths in a way that is portable between operating systems; dir/file
on Linux vs. dir\file
on Windows, for example.
import * as path from 'path';
// `join` should be used to construct paths in a
// portable way. It takes any number of arguments
// and constructs a hierarchical path from them.
const p = path.join('dir1', 'dir2', 'filename');
console.log('p:', p);
// You should always use `join` instead of
// concatenating `/`s or `\`s manually. In addition
// to providing portability, `join` will also
// normalize paths by removing superfluous separators
// and directory changes.
console.log(path.join('dir1//', 'filename'));
console.log(path.join('dir1/../dir1', 'filename'));
// `dirname` and `basename` can be used to split a path to the
// directory and the file. Alternatively, `parse` will
// return both in the same call.
console.log('Dir(p):', path.dirname(p));
console.log('Base(p):', path.basename(p));
// We can check whether a path is absolute.
console.log(path.isAbsolute('dir/file'));
console.log(path.isAbsolute('/dir/file'));
const filename = 'config.json';
// Some file names have extensions following a dot. We
// can split the extension out of such names with `extname`.
const ext = path.extname(filename);
console.log(ext);
// To find the file's name with the extension removed,
// use `basename` with a second argument.
console.log(path.basename(filename, ext));
// `relative` finds a relative path between a base and a
// target. It returns an error if the target cannot
// be made relative to base.
console.log(path.relative('a/b', 'a/b/t/file'));
console.log(path.relative('a/b', 'a/c/t/file'));
To run the program:
$ ts-node file-paths.ts
p: dir1/dir2/filename
dir1/filename
dir1/filename
Dir(p): dir1/dir2
Base(p): filename
false
true
.json
config
t/file
../c/t/file
Note that in TypeScript (running on Node.js), we use the path
module instead of filepath
. The functions have slightly different names but similar functionality. For example, Join
becomes join
, Dir
becomes dirname
, Base
becomes basename
, Ext
becomes extname
, and Rel
becomes relative
.
Also, TypeScript doesn’t have a direct equivalent to Go’s error handling with multiple return values. In cases where error handling is needed, you would typically use try-catch blocks or work with Promises.