var path = 'public/uploads/file.txt',
buffer = new Buffer("some content\n");
fs.open(path, 'w', function(err, fd) {
if (err) {
throw 'error opening file: ' + err;
}
fs.write(fd, buffer, 0, buffer.length, null, function(err) {
if (err) throw 'error writing file: ' + err;
fs.close(fd, function() {
console.log('file written');
})
});
});
Как читать объяснять?
fs.open(filepath, 'r', function(err, fd) {
fs.fstat(fd, function(err, stats) {
var bufferSize=stats.size,
chunkSize=512,
buffer=new Buffer(bufferSize),
bytesRead = 0;
while (bytesRead < bufferSize) {
if ((bytesRead + chunkSize) > bufferSize) {
chunkSize = (bufferSize - bytesRead);
}
fs.read(fd, buffer, bytesRead, chunkSize, bytesRead);
bytesRead += chunkSize;
}
console.log(buffer.toString('utf8', 0, bufferSize));
fs.close(fd);
});
});
Принимаем по websocket файл с клиента:
// Convert a binary buffer into a "binary" encoded string.
function binaryEncode(buffer) {
var string = "";
for (var i = 0, l = buffer.length; i < l; i++) {
string += String.fromCharCode(buffer[i]);
}
return string
}
// Convert a "binary" encoded string into a binary buffer.
function binaryDecode(string) {
var length = string.length;
var buffer = new Buffer(length);
for (var i = 0; i < length; i++) {
buffer[i] = string.charCodeAt(i);
}
}
client.on('stream', function(stream, meta){
var bufs = [];
stream.on('data', function(data){
bufs.push(data);
});
stream.on('end', function(){
var buf = binaryEncode(Buffer.concat(bufs));
fs.writeFile(__dirname + "/tmp/"+meta.frame+".dat", buf, "binary", function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
});
}