Search code examples
esp8266arduino-esp8266esp32

How to "find and replace" strings in a file from SPIFFS on ESP8266/ESP32?


I am running a little web server on the ESP-32 and having the HTML files on the flash memory accessing it by SPIFFS. I have some status fields which I would like to insert dynamically into the static HTML files. Therefore I defined some custom placeholders like {data_recv} and {data_sent} which should be replaced by field values from the code and then being served by the web server to the client browser.

When a client browser requests one of the HTML pages, I am going to read them with SPIFFS like:

  if(SPIFFS.exists(path)) {                             // if the file exists
    File file = SPIFFS.open(path, "r");                 // open it

    // TODO: replace placeholders {data_recv} and {data_sent} with field values ...

    size_t sent = server.streamFile(file, contentType); // and send it to the client
    file.close();                                       // then close the file again
    return true;
  }

Some ideas how to implement a "find-and-replace" function for the File type?

Something with the following function signature:

bool findAndReplace(File file, String searchStr, String replaceStr) {
    // implementation ...
}

Solution

  • My suggestion would be not to rewrite the files but to replace the values while answering the requests.

    Instead of using server.streamFile(file, contentType) you would use a buffer to read the file block-wise using fread(buffer, 1, len, file), replace the pattern in the buffer (the tricky part is that you have to keep track of partial matches at the end of the buffer) and send the buffer to the client.