Last active
September 25, 2023 07:24
-
-
Save newbenhd/4be19fd0610673b31c679128878b3958 to your computer and use it in GitHub Desktop.
concat src files to destination file in order
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
/** | |
* Write the implementation of concatFiles(), a callback-style function that takes two or more paths | |
* to text files in the filesystem and a destination file: | |
* ```js | |
* function concatFiles (srcFile1, srcFile2, srcFile3, ..., dest, cb) { | |
* // ... | |
* } | |
* ``` | |
* This function must copy the contents of every source file into the destination file, respecting | |
* the order of the files, as provided by the arguments list. For instance, given two files, if the | |
* first file contains foo and the second file contains bar, the function should write foobar (and | |
* not barfoo) in the destination file. Note that the preceding example signature is not valid | |
* JavaScript syntax: you need to find a different way to handle an arbitrary number of arguments. | |
* For instance, you could use the rest parameters syntax. | |
*/ | |
function concatFiles(...args) { | |
if (args.length <= 2) throw Error('At least one source file, one destination file, and a callback') | |
const [destination, cb] = args.slice(-2) | |
const srcFiles = args.slice(0, -2) | |
const { readFile, appendFile } = require('fs') | |
const tasks = srcFiles.map(function(file) { | |
return function(callback) { | |
readFile(file, function(error, data) { | |
if (error) return cb(error) | |
appendFile(destination, data, function(appendError) { | |
if (appendError) return cb(error) | |
callback() | |
}) | |
}) | |
} | |
}) | |
iterator(0, tasks, cb) | |
} | |
function iterator(index, tasks, finish) { | |
if (index === tasks.length) return finish() | |
const task = tasks[index] | |
task(iterator.bind(null, index + 1, tasks, finish)) | |
} | |
function callback(error) { | |
if (error) return console.error(error.message) | |
console.log('done') | |
} | |
concatFiles.apply(null, process.argv.slice(2).concat(['dest.txt', callback])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment