Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrichardsz/e843901b83008107f317d83b22d971df to your computer and use it in GitHub Desktop.
Save jrichardsz/e843901b83008107f317d83b22d971df to your computer and use it in GitHub Desktop.
nodejs file snippets

Given a file with the text and replacement

windows, shit
microsoft, poop
c#, threw up
foo, bar

search_replace.js

const fs = require("fs");
const path = require("path");

function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

async function main(){
    console.log(process.argv)

    var allowedExtensions = [".cs"]//set here your own extensions

    var files = await fs.promises.readdir(process.argv[3], { recursive: true });
    files = files.filter(el => allowedExtensions.includes(path.extname(el)))
    
    var lines = await fs.promises.readFile(process.argv[2], "utf8")
    for(var line of lines.split("\n")){
        if(line.trim().length==0) continue;
        var parts = line.trim().split(",");
        for(var file of files){
            var content = await fs.promises.readFile(path.join(process.argv[3], file), "utf8")
            if(content.includes(parts[0].trim())){
                console.log(file, parts[0], parts[1])
                var myExp = new RegExp(escapeRegExp(parts[0]), 'g');
                //console.log(myExp)
                var newContent = content.replace(myExp, parts[1])
                await fs.promises.writeFile(path.join(process.argv[3], file), newContent)
            }
        }
    }
}

main();

usage

node research/search_replace.js /baz/data.csv /home/bart/code/acme

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