Use PHP functions in JavaScript

JavaScript fread

Binary-safe file read

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
function fread (handle, length) {
    // Binary-safe file read  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/fread    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
    // *     example 1: fread(handle, 10);
    // *     returns 1: '123'
    if (!this.php_js || !this.php_js.resourceData || !this.php_js.resourceDataPointer) {        return false;
    }
 
    length = length < 8192 ? (Math.floor(length / 2) || 1) : 4096; // 2 bytes per character (or surrogate) means limit of 8192 bytes = 4096 characters; ensure at least one
     var start = this.php_js.resourceDataPointer[handle.id];
 
    if (start === undefined) {
        return false; // Resource was already closed
    } 
    if (!this.php_js.resourceData[handle.id][start]) {
        return ''; // already reached the end of the file (but pointer not closed)
    }
     this.php_js.resourceDataPointer[handle.id] += length;
 
    return this.php_js.resourceData[handle.id].substr(start, length); // Extra length won't be a problem here
}
external links: original PHP docs | raw js source

Examples

Running

1
2
fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
fread(handle, 10);

Should return

1
'123'

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have fread goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

No comments yet. Be the first!


Contribute a New function

More functions

In this category

basename
dirname
fclose
feof
fgetc
fgetcsv
fgets
fgetss
file
file_exists
file_get_contents
filemtime
filesize
fopen
fpassthru
» fread
fscanf
fseek
ftell
pathinfo
pclose
popen
readfile
realpath
rewind

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: AYHAN BARI*, Nikita Ekshiyan, Nikita Ekshiyan, Petr Pavel, @HalfWinter, Paulo Freitas, Andros Peña Romo, @andorosu, Raimund Szabo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !