Skip to content

Instantly share code, notes, and snippets.

@newbenhd
Last active September 25, 2023 07:24
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 newbenhd/4be19fd0610673b31c679128878b3958 to your computer and use it in GitHub Desktop.
Save newbenhd/4be19fd0610673b31c679128878b3958 to your computer and use it in GitHub Desktop.
concat src files to destination file in order
/**
* 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