File Paths in JavaScript

Here’s the translation of the Go code example to JavaScript, formatted in Markdown 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.

const path = require('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.
let 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('dirname(p):', path.dirname(p));
console.log('basename(p):', path.basename(p));

// We can check whether a path is absolute.
console.log(path.isAbsolute('dir/file'));
console.log(path.isAbsolute('/dir/file'));

let filename = 'config.json';

// Some file names have extensions following a dot.
// We can split the extension out of such names with extname.
let ext = path.extname(filename);
console.log(ext);

// To find the file's name with the extension removed,
// use path.basename with the extension as the 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.
let rel = path.relative('a/b', 'a/b/t/file');
console.log(rel);

rel = path.relative('a/b', 'a/c/t/file');
console.log(rel);

To run the program:

$ node file-paths.js
p: dir1/dir2/filename
dir1/filename
dir1/filename
dirname(p): dir1/dir2
basename(p): filename
false
true
.json
config
t/file
../c/t/file

In this JavaScript version:

  1. We use the built-in path module, which provides similar functionality to Go’s filepath package.

  2. The Join function is replaced with path.join().

  3. Dir and Base are replaced with path.dirname() and path.basename() respectively.

  4. IsAbs is replaced with path.isAbsolute().

  5. Ext is replaced with path.extname().

  6. For removing the extension, we use path.basename() with two arguments instead of strings.TrimSuffix().

  7. Rel is replaced with path.relative().

  8. Error handling is different in JavaScript. The path.relative() function doesn’t throw an error, so we don’t need to use try-catch blocks.

This example demonstrates how to work with file paths in a cross-platform manner using JavaScript and Node.js.