Skip to content

Instantly share code, notes, and snippets.

@ronaldaug
Last active April 26, 2023 10:22
Show Gist options
  • Save ronaldaug/a116226a50f628aebf70d3a4895f1141 to your computer and use it in GitHub Desktop.
Save ronaldaug/a116226a50f628aebf70d3a4895f1141 to your computer and use it in GitHub Desktop.
Useful Nodejs functions without dependencies

Prompt to get the value

const { stdin, stdout } = process;

// Prompt function
function prompt(question) {
  return new Promise((resolve, reject) => {
    stdin.resume();
    stdout.write(question);

    stdin.on('data', data => resolve(data.toString().trim()));
    stdin.on('error', err => reject(err));
  });
}

// Init
async function init() {
    try {
        
      let value = await prompt('Please type something')

      console.log(value)

      stdin.pause();

    } catch(error) {
      console.log("There's an error!");
      console.log(error);
    }
    process.exit();
}

init();

Read File Content

/**
 * Read Files Content
 */
function readFileContents(dir) {
    const files = [];
    fs.readdirSync(dir).forEach(filename => {
        const data = fs.readFileSync(dir+'/'+filename, 'utf-8')
        files.push(data)
    });
    return files;
}

Copy Directory

function copyFolderSync(from, to) {
    fs.mkdirSync(to);
    fs.readdirSync(from).forEach(element => {
        if (fs.lstatSync(path.join(from, element)).isFile()) {
            fs.copyFileSync(path.join(from, element), path.join(to, element));
        } else {
            copyFolderSync(path.join(from, element), path.join(to, element));
        }
    });
}

Found word's line number

const content = `Lorem ipsum dolor, sit amet consectetur adipisicing elit. \n Facilis deleniti abc ipsam quibusdam odit.`;

const lineNumbers = (needle, haystack) => haystack
    .split(/^/gm)
    .map((v, i) => v.match(needle) ? i + 1 : 0)
    .filter(a => a);

console.log(lineNumbers('abc',content)) // [2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment