function sendMainPage(res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html lang="en">');
//chunk size
let bytesperChunk = 2048;
//cssN stores how many chunks i need to send
let cssN = Math.ceil(storage.read('main.css').length / bytesperChunk );
//cssI stores how many chunks are already send
let cssI = 0;
let htmlN = Math.ceil(storage.read('main.html').length / bytesperChunk );
let htmlI = 0;
res.on('drain', function(){
if (cssN == cssI) {
if (htmlN == htmlI) {
//Here is my client js code with all the values and the end of the html file
res.end(``);
print('end');
}else {
res.write(storage.read('main.html', htmlI * bytesperChunk , bytesperChunk ));
print(process.memory().free);
htmlI++;
}
}else {
res.write(storage.read('main.css', cssI * bytesperChunk , bytesperChunk ));
cssI++;
print(cssI);
}
});
}
I don't know if it's the best solution, but it works for me and when I request the page the loading time is only 2-3 seconds.
Not only that, but I still have 850 free blocks of ram, because now I don't need to load the long HTML string before I send it.
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
Thank you for your help @allObjects and @Robin.
I got it now working, and it's a good solution (for me).
The idea is from Best way to stream base64 encoded string to a web client and I used the drain event.
I saved the head and the body in the Storage module and send them chunk for chunk.
I don't know if it's the best solution, but it works for me and when I request the page the loading time is only 2-3 seconds.
Not only that, but I still have 850 free blocks of ram, because now I don't need to load the long HTML string before I send it.