phpjs
Version:
65 lines (51 loc) • 1.99 kB
Markdown
layout: page
title: "JavaScript fread function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/fread:775
- /functions/view/fread
- /functions/view/775
- /functions/fread:775
- /functions/775
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's fread
{% codeblock filesystem/fread.js lang:js https://raw.github.com/kvz/phpjs/master/functions/filesystem/fread.js raw on github %}
function fread (handle, length) {
// http://kevin.vanzonneveld.net
// + 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
}
{% endcodeblock %}
- [view on github](https://github.com/kvz/phpjs/blob/master/functions/filesystem/fread.js)
- [edit on github](https://github.com/kvz/phpjs/edit/master/functions/filesystem/fread.js)
### Example 1
This code
{% codeblock lang:js example %}
fopen('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm', 'r');
fread(handle, 10);
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
'123'
{% endcodeblock %}
### Other PHP functions in the filesystem extension
{% render_partial _includes/custom/filesystem.html %}