Filesystem

Flash layout

Even though file system is stored on the same flash chip as the program,programming new sketch will not modify file system contents. This allowsto use file system to store sketch data, configuration files, or contentfor Web server.

The following diagram illustrates flash layout used in Arduinoenvironment:

|--------------|-------|---------------|--|--|--|--|--|^^^^^SketchOTAupdateFilesystemEEPROMWiFiconfig(SDK)

File system size depends on the flash chip size. Depending on the boardwhich is selected in IDE, you have the following options for flash size:

BoardFlash chip size, bytesFile system size, bytes
Generic module512k64k, 128k
Generic module1M64k, 128k, 256k, 512k
Generic module2M1M
Generic module4M3M
Adafruit HUZZAH4M1M, 3M
ESPresso Lite 1.04M1M, 3M
ESPresso Lite 2.04M1M, 3M
NodeMCU 0.94M1M, 3M
NodeMCU 1.04M1M, 3M
Olimex MOD-WIFI-ESP8266(-DEV)2M1M
SparkFun Thing512k64k
SweetPea ESP-2104M1M, 3M
WeMos D1 & D1 mini4M1M, 3M
ESPDuino4M1M, 3M

Note: to use any of file system functions in the sketch, add thefollowing include to the sketch:

#include "FS.h"

File system limitations

The filesystem implementation for ESP8266 had to accomodate theconstraints of the chip, among which its limited RAM.SPIFFS was selected because itis designed for small systems, but that comes at the cost of somesimplifications and limitations.

First, behind the scenes, SPIFFS does not support directories, it juststores a “flat” list of files. But contrary to traditional filesystems,the slash character'/' is allowed in filenames, so the functionsthat deal with directory listing (e.g.openDir("/website"))basically just filter the filenames and keep the ones that start withthe requested prefix (/website/). Practically speaking, that makeslittle difference though.

Second, there is a limit of 32 chars in total for filenames. One'\0' char is reserved for C string termination, so that leaves uswith 31 usable characters.

Combined, that means it is advised to keep filenames short and not usedeeply nested directories, as the full path of each file (includingdirectories,'/' characters, base name, dot and extension) has to be31 chars at a maximum. For example, the filename/website/images/bird_thumbnail.jpg is 34 chars and will cause someproblems if used, for example inexists() or in case another filestarts with the same first 31 characters.

Warning: That limit is easily reached and if ignored, problems mightgo unnoticed because no error message will appear at compilation norruntime.

For more details on the internals of SPIFFS implementation, see theSPIFFS readmefile.

Uploading files to file system

ESP8266FS is a tool which integrates into the Arduino IDE. It adds amenu item toTools menu for uploading the contents of sketch datadirectory into ESP8266 flash file system.

  • Download the tool:https://github.com/esp8266/arduino-esp8266fs-plugin/releases/download/0.3.0/ESP8266FS-0.3.0.zip.
  • In your Arduino sketchbook directory, createtools directory ifit doesn’t exist yet
  • Unpack the tool intotools directory (the path will look like<home_dir>/Arduino/tools/ESP8266FS/tool/esp8266fs.jar)
  • Restart Arduino IDE
  • Open a sketch (or create a new one and save it)
  • Go to sketch directory (choose Sketch > Show Sketch Folder)
  • Create a directory nameddata and any files you want in the filesystem there
  • Make sure you have selected a board, port, and closed Serial Monitor
  • Select Tools > ESP8266 Sketch Data Upload. This should startuploading the files into ESP8266 flash file system. When done, IDEstatus bar will displaySPIFFSImageUploaded message.

File system object (SPIFFS)

begin

SPIFFS.begin()

This method mounts SPIFFS file system. It must be called before anyother FS APIs are used. Returnstrue if file system was mountedsuccessfully, false otherwise.

end

SPIFFS.end()

This method unmounts SPIFFS file system. Use this method before updatingSPIFFS using OTA.

format

SPIFFS.format()

Formats the file system. May be called either before or after callingbegin. Returnstrue if formatting was successful.

open

SPIFFS.open(path,mode)

Opens a file.path should be an absolute path starting with a slash(e.g./dir/filename.txt).mode is a string specifying accessmode. It can be one of “r”, “w”, “a”, “r+”, “w+”, “a+”. Meaning of thesemodes is the same as forfopen C function.

rOpentextfileforreading.Thestreamispositionedatthebeginningofthefile.r+Openforreadingandwriting.Thestreamispositionedatthebeginningofthefile.wTruncatefiletozerolengthorcreatetextfileforwriting.Thestreamispositionedatthebeginningofthefile.w+Openforreadingandwriting.Thefileiscreatedifitdoesnotexist,otherwiseitistruncated.Thestreamispositionedatthebeginningofthefile.aOpenforappending(writingatendoffile).Thefileiscreatedifitdoesnotexist.Thestreamispositionedattheendofthefile.a+Openforreadingandappending(writingatendoffile).Thefileiscreatedifitdoesnotexist.Theinitialfilepositionforreadingisatthebeginningofthefile,butoutputisalwaysappendedtotheendofthefile.

ReturnsFile object. To check whether the file was openedsuccessfully, use the boolean operator.

File f = SPIFFS.open("/f.txt", "w");if (!f) {    Serial.println("file open failed");}

exists

SPIFFS.exists(path)

Returnstrue if a file with given path exists,false otherwise.

openDir

SPIFFS.openDir(path)

Opens a directory given its absolute path. Returns aDir object.

remove

SPIFFS.remove(path)

Deletes the file given its absolute path. Returnstrue if file wasdeleted successfully.

rename

SPIFFS.rename(pathFrom,pathTo)

Renames file frompathFrom topathTo. Paths must be absolute.Returnstrue if file was renamed successfully.

info

FSInfofs_info;SPIFFS.info(fs_info);

FillsFSInfo structure withinformation about the file system. Returnstrue is successful,false otherwise.

Filesystem information structure

structFSInfo{size_ttotalBytes;size_tusedBytes;size_tblockSize;size_tpageSize;size_tmaxOpenFiles;size_tmaxPathLength;};

This is the structure which may be filled using FS::info method. -totalBytes — total size of useful data on the file system -usedBytes — number of bytes used by files -blockSize — SPIFFSblock size -pageSize — SPIFFS logical page size -maxOpenFiles— max number of files which may be open simultaneously -maxPathLength — max file name length (including one byte for zerotermination)

Directory object (Dir)

The purpose ofDir object is to iterate over files inside a directory.It provides three methods:next(),fileName(), andopenFile(mode).

The following example shows how it should be used:

Dirdir=SPIFFS.openDir("/data");while(dir.next()){Serial.print(dir.fileName());Filef=dir.openFile("r");Serial.println(f.size());}

dir.next() returns true while there are files in the directory toiterate over. It must be called before callingfileName andopenFile functions.

openFile method takesmode argument which has the same meaning asforSPIFFS.open function.

File object

SPIFFS.open anddir.openFile functions return aFile object.This object supports all the functions ofStream, so you can usereadBytes,findUntil,parseInt,println, and all otherStream methods.

There are also some functions which are specific toFile object.

seek

file.seek(offset,mode)

This function behaves likefseek C function. Depending on the valueofmode, it moves current position in a file as follows:

  • ifmode isSeekSet, position is set tooffset bytes fromthe beginning.
  • ifmode isSeekCur, current position is moved byoffsetbytes.
  • ifmode isSeekEnd, position is set tooffset bytes fromthe end of the file.

Returnstrue if position was set successfully.

position

file.position()

Returns the current position inside the file, in bytes.

size

file.size()

Returns file size, in bytes.

name

Stringname=file.name();

Returns file name, asconstchar*. Convert it toString forstorage.

close

file.close()

Close the file. No other operations should be performed onFile objectafterclose function was called.