Skip to content

Instantly share code, notes, and snippets.

@r2abreu
Created January 23, 2024 15:30
Show Gist options
  • Save r2abreu/6f05dbac34085288b7ba04b38912adc4 to your computer and use it in GitHub Desktop.
Save r2abreu/6f05dbac34085288b7ba04b38912adc4 to your computer and use it in GitHub Desktop.
concatenation
import { PathLike, readFile, appendFile } from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { dirname } from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const files = process.argv.slice(2);
/**
* Sequential Iteration pattern with callbacks:
*
* Pseudo:
* iterate() {
* if (index === tasks.length) return
*
* task = tasks[index];
*
* task(() => iterate(index++));
* }
*
* iterate(0);
*/
function concatFiles(
files: string[],
dest: PathLike,
cb: (err: NodeJS.ErrnoException | null) => void
) {
function iterate(index: number) {
if (index === files.length) {
return cb(null);
}
readFileContentsAndAppend(files[index], dest, (err) => {
if (err) {
console.log("Error reading the file");
return cb(err);
}
iterate(++index);
});
}
iterate(0);
}
function readFileContentsAndAppend(
file: PathLike,
dest: PathLike,
cb: (err: NodeJS.ErrnoException | null) => void
) {
const filePath = path.join(__dirname, file.toString());
readFile(filePath, { encoding: "utf-8" }, (err, data) => {
if (err) {
if (err.code === "ENOENT") {
console.error(`The file "${file}" doesn't exist. Exiting`);
process.exit(1);
}
return cb(err);
}
appendFile(dest, data, (err) => {
if (err) {
return console.error("Error appending to dest file");
}
return cb(null);
});
});
}
concatFiles([...files], path.join(__dirname, "dest"), (err) => {
if (err) {
return console.error(err);
}
console.log("Files concatenated at destination");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment