|
|
@ -1,5 +1,6 @@ |
|
|
|
var sys = require('sys'), |
|
|
|
events = require('events'); |
|
|
|
events = require('events'), |
|
|
|
Buffer = require('buffer').Buffer; |
|
|
|
|
|
|
|
var binding = process.binding('fs'); |
|
|
|
var fs = exports; |
|
|
@ -38,34 +39,39 @@ fs.Stats.prototype.isSocket = function () { |
|
|
|
return this._checkModeProperty(process.S_IFSOCK); |
|
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
function readAll (fd, pos, content, encoding, callback) { |
|
|
|
binding.read(fd, 4*1024, pos, encoding, function (err, chunk, bytesRead) { |
|
|
|
if (err) { |
|
|
|
if (callback) callback(err); |
|
|
|
} else if (chunk) { |
|
|
|
content += chunk; |
|
|
|
pos += bytesRead; |
|
|
|
readAll(fd, pos, content, encoding, callback); |
|
|
|
} else { |
|
|
|
binding.close(fd, function (err) { |
|
|
|
if (callback) callback(err, content); |
|
|
|
}); |
|
|
|
} |
|
|
|
}); |
|
|
|
} |
|
|
|
|
|
|
|
fs.readFile = function (path, encoding_, callback) { |
|
|
|
var encoding = typeof(encoding_) == 'string' ? encoding_ : 'utf8'; |
|
|
|
var encoding = typeof(encoding_) == 'string' ? encoding_ : null; |
|
|
|
var callback_ = arguments[arguments.length - 1]; |
|
|
|
var callback = (typeof(callback_) == 'function' ? callback_ : null); |
|
|
|
var callback = (typeof(callback_) == 'function' ? callback_ : noop); |
|
|
|
binding.stat(path, function (err, stat) { |
|
|
|
if (err) { callback(err); return; } |
|
|
|
binding.open(path, process.O_RDONLY, 0666, function (err, fd) { |
|
|
|
if (err) { |
|
|
|
if (callback) callback(err); |
|
|
|
if (err) { callback(err); return; } |
|
|
|
var size = stat.size; |
|
|
|
var buffer = new Buffer(size); |
|
|
|
var offset = 0; |
|
|
|
function doRead() { |
|
|
|
// position is offset or null so we can read files on unseekable mediums
|
|
|
|
binding.read(fd, buffer, offset, size - offset, offset || null, function (err, amount) { |
|
|
|
if (err) { callback(err); return; } |
|
|
|
if (amount + offset < size) { |
|
|
|
offset += amount; |
|
|
|
doRead(); |
|
|
|
return; |
|
|
|
} |
|
|
|
if (encoding) { |
|
|
|
try { |
|
|
|
callback(null, buffer.toString(encoding)); |
|
|
|
} catch (err) { |
|
|
|
callback(err); |
|
|
|
} |
|
|
|
} else { |
|
|
|
// leave pos null to allow reads on unseekable devices
|
|
|
|
readAll(fd, null, "", encoding, callback); |
|
|
|
callback(null, buffer); |
|
|
|
} |
|
|
|
}); |
|
|
|
} |
|
|
|
doRead(); |
|
|
|
}); |
|
|
|
}); |
|
|
|
}; |
|
|
|
|
|
|
|