Friday 17 March 2017

Node/JavaScript function to return a new path, given a filepath, basepath and new destpath

What custom function can be used (in node) whereby if passed three arguments, namely filePath, basePath and destPath it returns a new path. For example.

Example function signature

var path = require('path'); // Nodes `path` module is likely to help?

/**
 * Returns a new filepath
 * @param {String} filePath - The path to the source file.
 * @param {String} basePath - The path to determine which part of the
 *     FilePath argument is to be appended to the destPath argument.
 * @param {String} destPath - The destination file path.
 * @return {String} The new filepath.
 */
function foo(filePath, basePath, destPath) {

    // ... ?

    return newFilePath;
}

Example usage:

Below are some examples of invoking the function and the value I'd expect returned given the arguments passed:

// Example A

var a = foo('./foo/bar/baz/quux/filename.json', 'foo/bar/baz/', './dist');

console.log(a) // --> 'dist/baz/quux/filename.json' 

// Example B

var b = foo('./a/b/c/d/e/filename.png', './a/b/c', './images/logos/');

console.log(b) // --> 'images/logos/c/d/e/filename.png' 

// Example C

var c = foo('images/a/b/filename.png', './images/a/b', 'pictures/');

console.log(c) // --> 'pictures/b/filename.png' 

Further info

  1. As you can see from the example function invocations the basePath String will inform the function where the filePath value should be trimmed, and its purpose is akin to the gulp base option used with thegulp.src() function.
  2. The argument String values (i.e. paths) will always be relative, however, they will sometimes include the current directory prefix ./ and sometimes not. The trailing forward slash / may or may not be present on the path String.
  3. The solution must work cross platform without any additional dependencies. It also must be usable with early node versions ( >= 0.10.28 )
  4. I've had various failed attempts using the utilities of the path module, such path.normalize then splitting the Array etc, etc. However, I'm quite certain the path module will be utilized in the solution.

Thanks in advance.



via RobC

No comments:

Post a Comment