Skip to content

Instantly share code, notes, and snippets.

@bostonou
Last active October 21, 2018 20:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bostonou/a54c029fa6f29459eafe to your computer and use it in GitHub Desktop.
Save bostonou/a54c029fa6f29459eafe to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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