0

I'm building a code playground for fun like jsfiddle. One thing I'm not so familiar with is url shortening where a unique string of characters is generated ie jsfiddle.net/QyqvC/ .

I believe I found a node.js solution for this here: http://pravin.paratey.com/posts/building-url-shortener However, I'm not sure how to make it so that when the url with the unique characers like this one "jsfiddle.net/QyqvC/ ", is visited, the data that's suppose to load for that specific page (html, css, javascript in their boxes) will load like with jsfiddle.

One solution I thought of was generating unique characters in javascript then having a js script modify the url from mysite.com to mysite.com/AqUeFg with those unique characters and then storing the code that's currently in the code boxes (html, js, css) along with those unique characters (AqUeFg) in my database and then I would have a self invoking anonymous function that would check for the unique characters at the end of the url after "/" when a page loads and then this would be used to find the data in my db (html, css, js) and display it in the appropriate boxes.

I'm not sure if this solution is any good. Is there a better way to do this? I feel like there probably is and also, with whatever solution I use, how can I avoid a scenario where I run out of unique characters?

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • First of all, this isn't url shortening, because..well, you don't shorten any url, you're just making a unique id. Second, how else did you think you were going to get data? Based on what? How will you know which pieces to fetch? – Zirak Sep 21 '13 at 07:54
  • 1
    _"how can I avoid a scenario where I run out of unique characters?"_ If you have a fixed length for the id string then obviously it has a fixed number of possible combinations of characters and so in theory you'll eventually run out - except that there would be so many billions of combinations that that won't happen for a _very_ long time... – nnnnnn Sep 21 '13 at 07:54

1 Answers1

0

I suppose the easiest way would be to base64 encode it.

var uri = new Buffer('your-slug').toString('base64');

There are tons of other solutions floating around the net too.

Rob
  • 12,659
  • 4
  • 39
  • 56
  • 1
    If you just want to convert a string to base64, you have [`btoa`](https://developer.mozilla.org/en-US/docs/Web/API/window.btoa) – Zirak Sep 21 '13 at 07:56
  • From the way the OP describes the problem he or she isn't actually trying to shorten or encode an existing plain English string, the idea is just to generate unique ids like jsfiddle does. – nnnnnn Sep 21 '13 at 07:58
  • @user2801524 [here is a pretty good explanation](http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener) of the process. – Rob Sep 21 '13 at 08:02