moefinley
moefinley

Reputation: 1329

Path manipulation in NodeJS

I want to create some new paths by modifying a copy of an existing path. The Node path object seems very basic. I can see how it's possible with the default path object but it seems clunky.

What is the neatest way to change

a/path/to/file.json

Into two other paths

a/path/to/file-original.json

a/path/to/file-comparand.json

The path could be relative or absolute so I'm hoping for something that just allows me to change the name without having to worry about root or dir objects.

Is there an Advanced Path module or something else I'm missing?

Thanks for any help

Upvotes: 2

Views: 2512

Answers (2)

GPX
GPX

Reputation: 3645

In addition to @joe's answer, here's a simpler version that needs the modify-filename package.

var modifyFilename = require('modify-filename');
const originalPath = "a/path/to/file.json";

const originalFilename = modifyFilename(originalPath, (name, ext) => {
    return `${name}-original${ext}`;
});

const comparandFilename = modifyFilename(originalPath, (name, ext) => {
    return `${name}-comparand${ext}`;
});

Upvotes: 0

Joe Clay
Joe Clay

Reputation: 35787

Assuming there's not a library which will implement this functionality for you, using path.parse doesn't have to be clunky - I actually think using that is probably the cleanest way of doing this:

let { dir, name, ext } = path.parse("a/path/to/file.json");
let path1 = path.join(dir, name + "-original" + ext);
let path2 = path.join(dir, name + "-comarand" + ext);

That code snippet uses destructuring, so you'll need a recent-ish version of Node to run it. That said, you could just replace that with accessing the parsed path object normally:

let p = path.parse("a/path/to/file.json");
let path1 = path.join(p.dir, p.name + "-original" + p.ext);
let path2 = path.join(p.dir, p.name + "-comarand" + p.ext);

Not that much worse!

If this is something you'd be doing frequently in your project, it wouldn't be too hard to lift it out into a utility function, like so:

function suffixFilename(path, suffix) {
    let { dir, name, ext } = path.parse(path);
    return path.join(dir, name + "-" + suffix + ext);
}

let path1 = suffixFilename("a/path/to/file.json", "original");
let path2 = suffixFilename("a/path/to/file.json", "comparand");

Upvotes: 1

Related Questions