I am trying to make a function that takes a file path and returns its content as a string. Here is my code snippet:
(defn get-string-from-file-path [path]
(let [fs (node/require "fs") c (chan)]
(.readFile fs path "utf8" (fn [err data] ((go (>! c (str data))))))
(go (def r (str (<! c)))) ; is using def correct here?
r))
- Is using
def
correct/idiomatic on line 4? - After calling this function with a valid file path, I get the following error:
TypeError: (intermediate value)(intermediate value)(intermediate value)(...).call is not a function at repl:99:6 at tryToString (fs.js:414:3) at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:401:12)
Weirdly enough, if I call the function again I get the desired string content of the file! What is going on here?
EDIT: Here is the corrected function:
(defn get-string-channel-from-file-path [path] ; function is now "get string channel" instead of "get string"
(let [fs (node/require "fs") c (chan)]
(.readFile fs path "utf8" (fn [err data] (go (>! c data))))
c)) ; return channel instead of string