File system
PandJS has a limited set of APIs for reading and writing files. All function are heavily inspired by POSIX-like APIs.
Open file
Open and possibly create a file. The exact behavior depends on the flags provided.
Returns FileHandle
class instance.
Check open(2) for more details.
You can also pass mode
parameter to open
function:
Available open flags:
- O_CREAT: Creates the file if it does not already exist.
- O_RDONLY: Opens the file in read-only mode, allowing data to be read but not written.
- O_WRONLY: Opens the file in write-only mode, allowing data to be written but not read.
- O_APPEND: Opens the file in append mode, with all writes added to the end of the file.
- O_EXCL: Ensures that the file is created exclusively; used with O_CREAT, it will cause an error if the file already exists.
- O_RDWR: Opens the file in read-write mode, allowing both reading from and writing to the file.
- O_TRUNC: Truncates the file’s content to zero length if it already exists and is opened in write or read-write mode.
Reading bytes from file
This snippet demonstrates the read method by reading up to 1024
bytes from an already-opened file into a buffer.
The read
method returns number of bytes actually read.
The read method is asynchronous, so it returns the data only once the reading process is complete.
Check read(2) for more details.
Writing bytes to file
Write method will try to write whole provided buffer to the file. Returns actually written bytes, so partial writes are possible - make sure you check if everything is written.
Check write(2) for more details.
Close file
Close every file when all operations are completed. If you forget to close file, it will lead to resource leak.
Check close(2) for more details.