I am experimenting a bit with the http server (espruino versions from 1.99) and this snippet works most of the time.
First time the page is opened it shows the files in the system as hyperlinks. Downloading a file many times breaks the code.
I´ve found that calling E.openFile many times in the left webide pane makes it fail too. No examples show a close method after openFile, so I believe that it is not needed.
var fs = require("fs");
try {
fs.readdirSync();
} catch (e) {
console.log('Formatting FS - only need to do once');
E.flashFatFS({ format: true });
fs.writeFileSync("xx.txt", "..");
}
function onPageRequest(req, res) {
var a = url.parse(req.url, true);
print(a);
if (a.pathname.substr(-1)=="/") { // a slash at the end, list the directory
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("<html><body><p>Contents of "+a.pathname+"</p><ul>");
fs.readdir().map(function(f) {
res.write('<a href="'+f+'">'+f+'</a>');
});
res.end("</ul></body></html>");
} else { // No slash, try and open file
var f = E.openFile(a.pathname, "r");
if (f !== undefined) { // File open succeeded - send it!
res.writeHead(200, {'Content-Type': 'text/plain'});
f.pipe(res); // streams the file to the HTTP response
} else { // couldn't open file
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end("404: Page "+a.pathname+" not found");
}
}
}
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.
Hello everybody,
I am experimenting a bit with the http server (espruino versions from 1.99) and this snippet works most of the time.
First time the page is opened it shows the files in the system as hyperlinks. Downloading a file many times breaks the code.
I´ve found that calling E.openFile many times in the left webide pane makes it fail too. No examples show a close method after openFile, so I believe that it is not needed.
Am I doing it wrong?