Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly generate junk data of certain size in Javascript

I am writing an upload speed test in Javascript. I am using Jquery (and Ajax) to send chunks of data to a server in order to time how long it takes to get a response. This should, in theory give an estimation, of the upload speed.

Of course to cater for different bandwidths of the user I sequentially upload larger and larger amounts of junk data until a threshold duration is reached. Currently I generate the junk data using the following function, however, it is very slow when generation megabytes of data.

function generate_random_data(size){
    var chars = "abcdefghijklmnopqrstuvwxyz";
    var random_data = "";
    for (var i = 0; i < size; i++){
        var random_num = Math.floor(Math.random() * char.length);
        random_data = random_data + chars.substring(random_num,random_num+1);
    }
    return random_data;
}

Really all I am doing is generating a chunk of bytes to send to the server, however, this is the only way I could find out how in Javascript.

Any help would be appreciated.

Update: I have re-written my code to make it just a repetition of a 10 byte string instead of a completely random string.

function generate_random_data(attempt){
    var table = {
        '1':10, //10kb  
        '2':12, //40kb
        '3':14, //160kb
        '4':16, //640kb
        '5':18, //2.5Mb
        '6':20 //10Mb
    }
    var random_data = "abcdefghij";  //10 bytes
    for (i = 0; i < table[attempt]; i++){
        random_data += random_data;
    }
    return random_data;

Now the function takes an argument of the attempt number (so the first time my script tries to upload it'll do the smallest file, then the next smallest, so-on and so-forth). It then gets a 10 byte string and then keeps adding it to itself until the desired length is reached.

Is this the best way? Is there a better way?

like image 541
user1357607 Avatar asked Mar 06 '26 08:03

user1357607


2 Answers

If you want to generate data to upload, and don't care about it being random, there is a way to do it using a Blob object

// Size should be given in 'bytes'
function generate_random_data(size) {
    return new Blob([new ArrayBuffer(size)], {type: 'application/octet-stream'});
};

I recently used this to test my upload speed against http://httpbin.org/post

like image 95
Jose Arandi Avatar answered Mar 07 '26 23:03

Jose Arandi


If you're looking for something like the answer from Jose Arandi but for NodeJS, you can use Buffer.

Buffer.alloc(10) gives you 10 zero bytes. Buffer.allocUnsafe(10) does not initialize the buffer, giving you 10 "random" bytes.

like image 26
Arno Hilke Avatar answered Mar 07 '26 21:03

Arno Hilke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!