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 } |
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.
No comments yet. Be the first!
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>