Created
September 15, 2014 09:50
-
-
Save homam/c2989056fefce2321b08 to your computer and use it in GitHub Desktop.
Find and Replace in String and Files in JavaScript
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
fs = require \fs | |
{map} = require \prelude-ls | |
{promises: {new-promise, parallel-limited-sequence, from-error-value-callback, from-void-callback, promise-monad}} = require \async-ls | |
find-and-repalce = (regex, replacement, file) --> | |
new-file = "" | |
last-index = 0 | |
while m = regex.exec file | |
new-file := new-file + (file.substring last-index, m.index) + replacement m | |
last-index := m.index + m.0.length | |
new-file + file.substring last-index, file.length | |
find-and-repalce-file = (regex, replacement, path) --> | |
file <- promise-monad.bind (from-error-value-callback fs.read-file, fs) path, encoding: \utf8 | |
new-file = find-and-repalce regex, replacement, file | |
(from-void-callback fs.write-file, fs) path, new-file, encoding: \utf8 | |
find-and-repalce-many-files = (regex, replacement, paths) --> | |
parallel-limited-sequence 4, (paths |> map find-and-repalce-file regex, replacement) | |
# example: | |
find-and-repalce-many-files /\[\{\(e(.+?)\)\}\]/gi , (-> "[{(e" + (it?.1?.replace /\s/ig, '') + ")}]"), ['file1', 'file2'] | |
..then -> console.log 'done!' | |
..catch -> console.log "error = ", arguments |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment