This module implements asynchronous file reading and writing.
import std/[asyncfile, asyncdispatch, os] proc main() {.async.} = var file = openAsync(getTempDir() / "foobar.txt", fmReadWrite) await file.write("test") file.setFilePos(0) let data = await file.readAll() doAssert data == "test" file.close() waitFor main()
Procs
proc getFilePos(f: AsyncFile): int64 {....raises: [], tags: [], forbids: [].}
- Retrieves the current position of the file pointer that is used to read from the specified file. The file's first byte has the index zero. Source Edit
proc getFileSize(f: AsyncFile): int64 {....raises: [OSError], tags: [], forbids: [].}
- Retrieves the specified file's size. Source Edit
proc newAsyncFile(fd: AsyncFD): AsyncFile {....raises: [OSError], tags: [], forbids: [].}
- Creates AsyncFile with a previously opened file descriptor fd. Source Edit
proc read(f: AsyncFile; size: int): Future[string] {. ...raises: [ValueError, Exception], tags: [RootEffect], forbids: [].}
-
Read size bytes from the specified file asynchronously starting at the current position of the file pointer. size should be greater than zero.
If the file pointer is past the end of the file then an empty string is returned.
Source Edit proc readBuffer(f: AsyncFile; buf: pointer; size: int): Future[int] {. ...raises: [ValueError, Exception], tags: [RootEffect], forbids: [].}
-
Read size bytes from the specified file asynchronously starting at the current position of the file pointer.
If the file pointer is past the end of the file then zero is returned and no bytes are read into buf
Source Edit proc readToStream(f: AsyncFile; fs: FutureStream[string]): owned( Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect], forbids: [].}
- Writes data to the specified future stream as the file is read. Source Edit
proc setFilePos(f: AsyncFile; pos: int64) {....raises: [], tags: [], forbids: [].}
- Sets the position of the file pointer that is used for read/write operations. The file's first byte has the index zero. Source Edit
proc setFileSize(f: AsyncFile; length: int64) {....raises: [OSError], tags: [], forbids: [].}
- Set a file length. Source Edit
proc writeFromStream(f: AsyncFile; fs: FutureStream[string]): owned( Future[void]) {....stackTrace: false, raises: [Exception], tags: [RootEffect], forbids: [].}
-
Reads data from the specified future stream until it is completed. The data which is read is written to the file immediately and freed from memory.
This procedure is perfect for saving streamed data to a file without wasting memory.
Source Edit