0 down vote favorite I was following the book Nim in Action.
In Chapter 3, there was an example like this:
import asyncdispatch, asyncfile
proc readFiles() {.async.} =
var file = openAsync("/tmp/hello.py", fmReadWrite)
let data = await file.readAll()
echo(data)
await file.write("Hello!\n")
file.close()
waitFor readFiles()
The only change I've made to the example was replacing the file name with one that existed on my system.
The code was supposed to output the content of the opened file and write "Hello!\n" to it.
But when I ran it, the readAll always returned an empty string, which I verified by add assert len(data) > 0.
What can I change to do async read successfully?
Why do you not tell us that fmRead mode works fine?
import asyncdispatch, asyncfile
proc readFiles() {.async.} =
var file = openAsync("test.txt", fmRead)
#file.setFilePos(0)
let data = await file.readAll()
echo(data)
#await file.write("Hello!\n")
file.close()
waitFor readFiles()
So it may be not an async problem, but only related to fmReadWrite mode. ReadWrite file access can have unexpected results, I know that from some other languages. Maybe you can investigate it yourself further.
Well, it is not that difficult: Search in module system for fmReadWrite and you will see
fmReadWrite, ## Open the file for read and write access.
## If the file does not exist, it will be
## created. Existing files will be cleared!
So file is erased at startup! I guess this behaviour is not Nim specific, I may have seen it in other languages, it may be related to OS. Well, may be not that easy to detect for people without some experience and a will to discover unexpected result on their own.
Thanks a lot, that explains what I observed.
Maybe the author of the book should consider using a different mode in the example.
Hi, I've tried fmRead and it didn't work for me.
Note, if you use fmReadWrite once, then content of your existing file is deleted, so next try with plain fmRead gives empty result. I guess you discovered that yourself already, just for other readers.