Skip to content

Instantly share code, notes, and snippets.

@borkdude
Last active June 4, 2022 02:26
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save borkdude/a6427534ea76cd4e9222a76eb398b289 to your computer and use it in GitHub Desktop.
Save borkdude/a6427534ea76cd4e9222a76eb398b289 to your computer and use it in GitHub Desktop.
CLI app with ClojureScript on Node

First install clojure so the clj command will be available.

brew install clojure

Clone and move core.cljs to the right directory:

git clone https://gist.github.com/a6427534ea76cd4e9222a76eb398b289.git inc
cd inc
mkdir -p src/inc
mv core.cljs src/inc

To develop:

clj -m cljs.main --repl-env node
cljs.user=> (require '[inc.core])
cljs.user=> (inc.core/handle-input "1")
2
nil
;; change something in src/inc/core.cljs
cljs.user=> (require '[inc.core] :reload)
;; try the change

To compile the final output:

clj -m cljs.main --target node --output-to inc.js -O simple -c inc.core
chmod +x inc.js

Let's try!

$ time echo 1 | ./inc.js
2
echo 1  0.00s user 0.00s system 38% cpu 0.002 total
./inc.js  0.13s user 0.03s system 94% cpu 0.173 total

$ time ./inc.js 1
2
./inc.js 1  0.13s user 0.03s system 96% cpu 0.168 total

$ ./inc.js hello
Not a number: hello

$ echo $?
1

Yay.

(ns inc.core)
(def std-input (atom ""))
(defn handle-input
[s]
(let [n (js/parseFloat s)]
(if (js/isNaN n)
(do (println "Not a number:" s)
(js/process.exit 1))
(println (inc n)))))
(defn -main [& args]
(if-let [s (first args)]
(handle-input s)
(do
(.setEncoding js/process.stdin "utf8")
(.on js/process.stdin "data"
(fn [data]
(swap! std-input #(str % data))))
(.on js/process.stdin "end"
(fn []
(swap! std-input (fn [s]
(subs s 0 (dec (count s)))))
(handle-input @std-input))))))
(set! cljs.core/*main-cli-fn* -main)
{:deps
{org.clojure/clojurescript {:git/url "https://github.com/clojure/clojurescript.git"
:sha "2f233d633f6dc44823105fd544685fc4da43ac6c"}}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment