Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving unique names to files while uploading them

Tags:

node.js

I am developing an app, in which users can post pics. So I want to ensure that every time the pic gets unique name. In PHP I use to concatenate timestamp with userId. But in node.js I am not getting the method to convert timestamp to string. So kindly suggest a way to ensure that my files don't get duplicate names.

like image 939
Tirthankar Kundu Avatar asked Dec 11 '13 10:12

Tirthankar Kundu


2 Answers

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.

like image 56
Tom Avatar answered Nov 02 '22 18:11

Tom


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' 
like image 35
Adrian Kremer Avatar answered Nov 02 '22 17:11

Adrian Kremer