Cross Platform Portable Shell Scripts Using Node.js

Date: 2021-02-08

Source: Cross Platform Portable Shell Scripts Using Node.js

"use strict";

const shell = require("shelljs");

// Show preseint working directory using pwd
console.log("Current Directory", shell.pwd().toString());

// Navigate to a directory using cd
console.log("Navigating to temp folder inside current directory");
shell.cd('./temp');
console.log("New Current Directory", shell.pwd().toString());

console.log("Navigating back to project root");
shell.cd("..");
console.log("Current Directory", shell.pwd().toString());

// List all files/folders in a directory using ls
console.log("Files/Folders in Directory", shell.pwd().toString());
shell.ls("./").forEach(function(file) {
    console.log("-", file.toString());
});

// Output to terminal using echo
shell.echo("Making a directory name tempDir");
shell.mkdir("tempDir");

// Gets all lines from given file where the word total exists
const greppedLines = shell.grep("total", "./temp/file1.txt").toString().split('\n');

console.log("\nGrepped lines with word total");
greppedLines.forEach(function(line) {
    console.log("Line - ", line);
});

console.log("\nCopying file ./temp/file1.txt to ./temp/file1-copy.txt");
shell.cp("./temp/file1.txt", "./temp/file1-copy.txt");

console.log("\nReplacing in place all occurences of 'if' with 'but' in file");
shell.sed("-i", RegExp(/if/, "g"), "but", "./temp/file1-copy.txt");

console.log("\nDisplaying text of file using cat");
console.log(shell.cat("./temp/file1.txt").toString());

console.log("Grep lines with word 'total' from ./temp/file1.txt, then replace 'total' with 'totalReplaced' then output final file to ./temp/out.txt");
shell.grep("total", "./temp/file1.txt")
    .sed(RegExp(/total/, "g"), "totalReplaced")
    .to("./temp/out.txt");
46020cookie-checkCross Platform Portable Shell Scripts Using Node.js