Instantly share code, notes, and snippets.

Embed
What would you like to do?
line-seq in cljs
;; This is a macro, and must be in clojure. It's name and location is the same as
;; the cljs file, except with a .clj extension.
(ns cljs-made-easy.line-seq
(:refer-clojure :exclude [with-open]))
(defmacro with-open [bindings & body]
(assert (= 2 (count bindings)) "Incorrect with-open bindings")
`(let ~bindings
(try
(do ~@body)
(finally
(.closeSync cljs-made-easy.line-seq/fs ~(bindings 0))))))
;;--------------------------------------------------------------------------------
;; This is the normal cljs file
(ns cljs-made-easy.line-seq
(:require clojure.string)
(:require-macros [cljs-made-easy.line-seq :refer [with-open]]))
(def fs (js/require "fs"))
(defn- read-chunk [fd]
(let [length 128
b (js/Buffer. length)
bytes-read (.readSync fs fd b 0 length nil)]
(if (> bytes-read 0)
(.toString b "utf8" 0 bytes-read))))
(defn line-seq
([fd]
(line-seq fd nil))
([fd line]
(if-let [chunk (read-chunk fd)]
(if (re-find #"\n" (str line chunk))
(let [lines (clojure.string/split (str line chunk) #"\n")]
(if (= 1 (count lines))
(lazy-cat lines (line-seq fd))
(lazy-cat (butlast lines) (line-seq fd (last lines)))))
(recur fd (str line chunk)))
(if line
(list line)
()))))
@chrismurrph

This comment has been minimized.

chrismurrph commented Aug 6, 2018

Trying to use line-seq. I get an error on the line (def fs (js/require "fs")). The error is "Uncaught ReferenceError: require is not defined". Is this because I need to have somehow defined "fs" in the index.html file?

@chrismurrph

This comment has been minimized.

chrismurrph commented Aug 6, 2018

I've realised this is a node.js thing - it won't work in the browser as I was trying.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment