如何在JavaScript中通过块读取本地文件? [英] How to read a local file by chunks in JavaScript?

查看:174
本文介绍了如何在JavaScript中通过块读取本地文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个在我的本地硬盘驱动器大小为500字节的文件,我想从它读取前100个字节,而无需将整个文件加载到内存中。如何在JavaScript中借助 UniversalXPConnect 完成这个工作?假设你想要读取ASCII文本数据(不需要字符集转换):

p>

  var file = Components.classes [@ mozilla.org/file/local;1] 
.createInstance(Components .interfaces.nsILocalFile);
file.initWithPath(/ foo / bar);
var fstream = Components.classes [@ mozilla.org/network/file-input-stream; 1]
.createInstance(Components.interfaces.nsIFileInputStream);
fstream.init(file,-1,0,0);
var sstream = Components.classes [@ mozilla.org/scriptableinputstream;1]
.createInstance(Components.interfaces.nsIScriptableInputStream);
sstream.init(fstream);
var data = sstream.read(100);
sstream.close();

更多信息: https://developer.mozilla.org/zh/Code_snippets/File_I%2F%2FO


Say, I have a file that is 500 bytes in size on my local hard drive and I want to read first 100 bytes from it without loading the whole file into memory. How to accomplish that in JavaScript with the help of UniversalXPConnect? In Firefox only, of course.

解决方案

Assuming that you want to read ASCII text data (no character set conversion):

var file = Components.classes["@mozilla.org/file/local;1"]
                     .createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("/foo/bar");
var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"]
                        .createInstance(Components.interfaces.nsIFileInputStream);
fstream.init(file, -1, 0, 0);
var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"]
                        .createInstance(Components.interfaces.nsIScriptableInputStream);
sstream.init(fstream);
var data = sstream.read(100);
sstream.close();

Further information: https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO

这篇关于如何在JavaScript中通过块读取本地文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆