const fs = require('fs');
// Read file
const filePath1 = 'test-file1.txt';
fs.open(filePath1, 'r', function (error, fd) {
if (error) {throw error;}
console.log('File 1 opened');
fs.fstat(fd, function (error, stat) {
if (error) {throw error;}
const fileSize = stat.size;
let chunkSize = 2; // 512; // in bytes
let fileBuffer = Buffer.alloc(fileSize);
let totalBytesRead = 0;
function readDataFromFile () {
if (totalBytesRead < fileSize) {
if ((totalBytesRead + chunkSize) > fileSize) {
chunkSize = fileSize - totalBytesRead;
}
fs.read(fd, fileBuffer, totalBytesRead, chunkSize, totalBytesRead, function (error, chunkBytesRead, buffer) {
if (error) {throw error;}
totalBytesRead += chunkSize;
console.log(buffer.toString('utf8', 0, fileSize));
readDataFromFile();
});
} else {
fs.close(fd, function (error) {
if (error) {throw error;}
console.log('File 1 closed');
});
}
}
readDataFromFile();
});
});
// Write file from string
const filePath2 = 'test-file2.txt';
fs.open(filePath2, 'w', function (error, fd) {
if (error) {throw error;}
console.log('File 2 opened');
fs.fstat(fd, function (error, stat) {
if (error) {throw error;}
const data = 'abcdefghijklmnopqrstuvwxyz';
let chunkSize = 1; // in characters
const dataSize = data.length;
let totalCharactersWritten = 0;
let chunk = data.slice(0, chunkSize);
function writeDataToFile () {
if (totalCharactersWritten < dataSize) {
fs.write(fd, chunk, totalCharactersWritten, 'utf8', function (error, chunkCharactersWritten, string) {
if (error) {throw error;}
totalCharactersWritten += chunk.length;
console.log(string);
if ((totalCharactersWritten + chunkSize) > dataSize) {
chunkSize = dataSize - totalCharactersWritten;
}
chunk = data.slice(totalCharactersWritten, totalCharactersWritten + chunkSize);
writeDataToFile();
});
} else {
fs.close(fd, function (error) {
if (error) {throw error;}
console.log('File 2 closed');
});
}
}
writeDataToFile();
});
});
// Write file from buffer
const filePath3 = 'test-file2.txt';
fs.open(filePath3, 'w', function (error, fd) {
if (error) {throw error;}
console.log('File 3 opened');
fs.fstat(fd, function (error, stat) {
if (error) {throw error;}
const data = Buffer.from('abcdefghijklmnopqrstuvwxyz');
let chunkSize = 2; // in bytes
const dataSize = data.length;
let totalBytesWritten = 0;
let chunk = data.slice(0, chunkSize);
function writeDataToFile () {
if (totalBytesWritten < dataSize) {
fs.write(fd, chunk, 0, chunkSize, totalBytesWritten, function (error, chunkBytesWritten, buffer) {
if (error) {throw error;}
totalBytesWritten += chunkSize;
console.log(buffer.toString('utf8'));
if ((totalBytesWritten + chunkSize) > dataSize) {
chunkSize = dataSize - totalBytesWritten;
}
chunk = data.slice(totalBytesWritten, totalBytesWritten + chunkSize);
writeDataToFile();
});
} else {
fs.close(fd, function (error) {
if (error) {throw error;}
console.log('File 3 closed');
});
}
}
writeDataToFile();
});
});
Комментариев нет:
Отправить комментарий