Giving unique names to files while uploading them

In node:

timestamp = new Date().getTime().toString();

One of the solutions would be to use UUID for a file name. But that of course depends on your applications requirements or constraints (naming convention etc.). However, if UUID as a file name would be acceptable, I recommend using node-uuid library (very easy to use!).

Sample code:

var uuidv4 = require('uuid/v4');
var filename = uuidv4() + '.png'

It is safe to use UUID as a unique identifier. You can find more on that on SO e.g. How unique is UUID?

Alternative solution (where name uniqueness is a requirement) would be to use another node.js library: flake-idgen which generates conflict-free ids based on the current timestamp. That solution guarantees unique numbers.

The solution is also very efficient, allows to generate up to 4096 ids in a millisecond per generator (you can have up to 1024 unique generators).

I hope that will help.


If you want to use timestamp uuid's use this

var uuid = require('uuid');

// Generate a v1 (time-based) id 
uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

// Generate a v4 (random) id 
uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

Tags:

Node.Js