cphill cphill - 2 months ago 8
Node.js Question

Nodejs Converting url string to only use path name

I am trying to determine the best way to split the url that is being passed to my form field before it is stored in my database. My thought process is to create a function that captures the value and then use the "Path" Nodejs module to split the string into just the url path and return that value, but I'm not sure if this is the best module to use.

Here is the format that my string will appear in:

https://bucket-test.s3.amazonaws.com/path/bucket/file.ext


What I am trying to capture with my function is this portion:
/path/bucket/file.ext


Here is my current function setup:

function cloudFrontUrl(s3url) {
var s3UrlPath = path.parse(s3url);
console.log('S3 URL Path ' + s3UrlPath);
return s3UrlPath;
}

Answer

Since you're parsing a full URL, you will probably want to use the built-in url module instead:

var urlparse = require('url').parse;

function cloudFrontUrl(s3url) {
  // or use `.path` if you want to include the query string, if it exists
  var s3UrlPath = urlparse(s3url).pathname;

  console.log('S3 URL Path ' + s3UrlPath);
  return s3UrlPath;
}