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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With