Last active
October 21, 2018 20:54
-
-
Save bostonou/a54c029fa6f29459eafe to your computer and use it in GitHub Desktop.
line-seq in cljs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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) | |
())))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've realised this is a node.js thing - it won't work in the browser as I was trying.