我尝试使用这样的sdk fs:
var fs = require('sdk/io/fs');
fs.readFile(filepath, 'utf-8', function (error, data) {
if (components.isSuccessCode(error)) {
var lines = data.toString().split(/[\r\n]+/);
for (var i = 0; i < lines.length; i++) {
listener.process(lines[i]);
}
}
else {
callback({error: error});
}
}
但我只得到2个文件的第一个符号(2 mb)。为什么我会出现这种奇怪的行为?
来自sdk的readFile声明:
function readFile(path, encoding, callback) {
if (isFunction(encoding)) {
callback = encoding
encoding = null
}
let buffer = null;
try {
let readStream = new ReadStream(path);
readStream.on("data", function(data) {
if (!buffer){
buffer = data;
}
else{
buffer = Buffer.concat([buffer, data], 2);
}
});
readStream.on("error", function onError(error) {
callback(error);
});
readStream.on("end", function onEnd() {
// Note: Need to destroy before invoking a callback
// so that file descriptor is released.
readStream.destroy();
callback(null, buffer);
});
}
catch (error) {
setTimeout(callback, 0, error);
}
};
答案 0 :(得分:0)
不要使用fs.readFile使用OS.file:https://developer.mozilla.org/en-US/docs/JavaScript_OS.File/OS.File_for_the_main_thread