https://stackoverflow.com/questions/10049557/reading-all-files-in-a-directory-store-them-in-objects-and-send-the-object
978579
function promiseAllP(items, block) {
    var promises = [];
    items.forEach(function(item,index) {
        promises.push( function(item,i) {
            return new Promise(function(resolve, reject) {
                return block.apply(this,[item,index,resolve,reject]);
            });
        }(item,index))
    });
    return Promise.all(promises);
}
968324
function (dir) {
    let files = [];
    let list = fs.readdirSync(dir);
    list.forEach(function (file) {
        file = dir + '/' + file;
        let stat = fs.statSync(file);
        if (stat && stat.isDirectory()) files = files.concat(walk(file));
        else files.push(file);
    });
    return files;
}
384414
public function dir_readdir()
    {
        $object = current($this->blobs);
        if ($object !== false) {
            next($this->blobs);
            return $object->getName();
        }
        return false;
    }
264749
function readFiles(filePath, fileType, callback) {
    if (path_1.extname(filePath) === fileType) {
        callback(filePath);
    }
    else if (fs_1.lstatSync(filePath).isDirectory()) {
        // src is directory
        var filesOrDirectories = fs_1.readdirSync(filePath);
        filesOrDirectories.map(function (fileName) {
            var fileOrDirectory = path_1.join(filePath, fileName);
            readFiles(fileOrDirectory, fileType, callback);
        });
    }
}
359246
function( options, callback ) {
            var me = this;
            var error = function(e) { fail(e); if ( callback ) me.fn( me.name, callback ).call( me, me ); };
            requestFileSystem( (options.storage === 'TEMPORARY' ? TEMPORARY : PERSISTENT), (options.size || 1024*1024*1024), function( fs ) {
                fs.root.getDirectory( options.name, {create:true}, function( directory ) {
                    filesystems[options.name] = directory;
                    if ( callback ) me.fn( me.name, callback ).call( me, me );
                }, error );
            }, error );
        }
425494
protected function sendZipFile()
  {
    if (!function_exists('ob_list_handlers') || ob_list_handlers()) {
      @ob_end_clean();
    }
    header("Content-Encoding: none");

    $this->checkConnector();
    $this->checkRequest();

    // empty wystarczy
    if ( empty($_GET['FileName']) ){
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
    }

    $resourceTypeInfo = $this->_currentFolder->getResourceTypeConfig();
    $hash = $resourceTypeInfo->getHash();
    if ( $hash !== $_GET['hash'] || $hash !== substr($_GET['FileName'],16,16) ){
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }

    if (!$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_VIEW)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
    }

    $fileName = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding(trim($_GET['FileName']));

    if (!CKFinder_Connector_Utils_FileSystem::checkFileName($fileName)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }

    if ( strtolower(pathinfo($fileName, PATHINFO_EXTENSION)) !== 'zip'){
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION);
    }

    $dest_dir = CKFinder_Connector_Utils_FileSystem::getTmpDir();
    $filePath = CKFinder_Connector_Utils_FileSystem::combinePaths($dest_dir,$fileName);
    if ( !file_exists($filePath) || !is_file($filePath)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
    }
    if (!is_readable($filePath)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
    }

    $zipFileName = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding(trim($_GET['ZipName']));
    if (!CKFinder_Connector_Utils_FileSystem::checkFileName($zipFileName)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }
    $fileFilename = pathinfo($zipFileName,PATHINFO_BASENAME );

    header("Content-Encoding: none");
    header("Cache-Control: cache, must-revalidate");
    header("Pragma: public");
    header("Expires: 0");
    $user_agent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";
    $encodedName = str_replace("\"", "\\\"", $fileFilename);
    if (strpos($user_agent, "MSIE") !== false) {
      $encodedName = str_replace(array("+", "%2E"), array(" ", "."), urlencode($encodedName));
    }
    header("Content-type: application/octet-stream; name=\"" . $fileFilename . "\"");
    header("Content-Disposition: attachment; filename=\"" . $encodedName. "\"");
    header("Content-Length: " . filesize($filePath));
    CKFinder_Connector_Utils_FileSystem::sendFile($filePath);
    exit;
  }
915359
public void send(Object object) {
        if (object instanceof File) {
            file((File) object);
        } else {
            send(object, getContentType());
        }
    }
1251922
function readDir(req, res, next){
  ls(req.PATH, (err, result) => {
    if(err) return next(err);
    res.apiOk(result);
  })
}
1053789
private void mkDir(String dir) throws Exception {
        Session session = getSession();
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();

        ChannelSftp c = (ChannelSftp) channel;
        if (!fileExists(dir, c))
            c.mkdir(dir);
        c.exit();
        session.disconnect();
    }
101826
function (directory, callback) {
        var that = this;
        fs.readdir(directory, function (err, files) {
            async.map(files, function langdir_iterator(file, next) {
                file = path.join(directory, file);
                fs.stat(file, function (err, stats) {
                    if (err || !stats.isDirectory()) return next(err);
                    var l = path.basename(file);
                    fs.readdir(file, function (err, files) {
                        if (err) return next(err);
                        async.map(files, function podir_iterator(file, next) {
                            file = path.join(directory, l, file);
                            fs.stat(file, function (err, stats) {
                                if (err || !stats.isFile()) return next(err);
                                that.loadLanguageFile(file, l, next);
                            });
                        }, next);
                    });
                });
            }, function langdir_done(err, results) {
                callback && callback(err);
            });
        });
    }
10568
def _join_all_filenames_and_text(
            self):
        
        self.log.info('starting the ``_join_all_filenames_and_text`` method')

        contentString = u""
        for i in self.directoryContents:
            contentString += u"%(i)s\n" % locals()
            if os.path.isfile(os.path.join(i)):
                if i[-4:] in [".png", ".jpg", ".gif"]:
                    continue
                readFile = codecs.open(i, encoding='ISO-8859-1', mode='r')
                if ".DS_Store" in i:
                    continue
                data = readFile.read()
                contentString += u"%(data)s\n" % locals()
                readFile.close()

        self.contentString = contentString

        self.log.info('completed the ``_join_all_filenames_and_text`` method')
        return None
587213
function crawlDirectoryWithFS(parent, sync) {
    return fsCmd('readdir', sync, parent).then(function (things) {
        return Q.all(things.map(function (file) {
            file = path.join(parent, file);
            return Q.all([file, fsCmd('stat', sync, file)]);
        }));
    }).then(function (stats) {
        return Q.all(stats.map(function (args) {
            var file = args[0], stat = args[1];
            if (stat.isDirectory()) {
                return crawlDirectoryWithFS(file, sync);
            }
            return file;
        }));
    }).then(function (grouped) {
        return [].concat.apply([], grouped);
    });
}
370558
function sendfile(res, file, options, callback) {
  var done = false;
  var streaming;

  // request aborted
  function onaborted() {
    if (done) return;
    done = true;

    var err = new Error('Request aborted');
    err.code = 'ECONNABORTED';
    callback(err);
  }

  // directory
  function ondirectory() {
    if (done) return;
    done = true;

    var err = new Error('EISDIR, read');
    err.code = 'EISDIR';
    callback(err);
  }

  // errors
  function onerror(err) {
    if (done) return;
    done = true;
    callback(err);
  }

  // ended
  function onend() {
    if (done) return;
    done = true;
    callback();
  }

  // file
  function onfile() {
    streaming = false;
  }

  // finished
  function onfinish(err) {
    if (err && err.code === 'ECONNRESET') return onaborted();
    if (err) return onerror(err);
    if (done) return;

    setImmediate(function () {
      if (streaming !== false && !done) {
        onaborted();
        return;
      }

      if (done) return;
      done = true;
      callback();
    });
  }

  // streaming
  function onstream() {
    streaming = true;
  }

  file.on('directory', ondirectory);
  file.on('end', onend);
  file.on('error', onerror);
  file.on('file', onfile);
  file.on('stream', onstream);
  onFinished(res, onfinish);

  if (options.headers) {
    // set headers on successful transfer
    file.on('headers', function headers(res) {
      var obj = options.headers;
      var keys = Object.keys(obj);

      for (var i = 0; i < keys.length; i++) {
        var k = keys[i];
        res.setHeader(k, obj[k]);
      }
    });
  }

  // pipe
  file.pipe(res);
}
650499
function _setDirectoryOpen(treeData, path, open) {
        var objectPath = _filePathToObjectPath(treeData, path),
            directory = treeData.getIn(objectPath);

        if (!objectPath) {
            return {
                needsLoading: true,
                treeData: treeData
            };
        }

        if (isFile(directory)) {
            return;
        }

        var alreadyOpen = directory.get("open") === true;

        if ((alreadyOpen && open) || (!alreadyOpen && !open)) {
            return;
        }

        treeData = treeData.updateIn(objectPath, function (directory) {
            if (open) {
                return directory.set("open", true);
            } else {
                return directory.delete("open");
            }
        });

        if (open && (directory.get("children") === null || directory.get("notFullyLoaded"))) {
            return {
                needsLoading: true,
                treeData: treeData
            };
        }
        return {
            needsLoading: false,
            treeData: treeData
        };
    }
956640
function getDirectoriesInURL()
{
	var trail = document.location.pathname.split( PATH_SEPARATOR );

	// check whether last section is a file or a directory
	var lastcrumb = trail[trail.length-1];
	for( var i = 0; i < FILE_EXTENSIONS.length; i++ )
	{
		if( lastcrumb.indexOf( FILE_EXTENSIONS[i] ) )
		{
			// it is, remove it and send results
			return trail.slice( 1, trail.length-1 );
		}
	}

	// it's not; send the trail unmodified
	return trail.slice( 1, trail.length );
}
400212
function() {
        var items = _utils.getArgArray(arguments);
        if (items.length === 0) {
            throw new Error('no files specified to create');
        }
        items.forEach(function(item) {
            var contents;
            var linkTarget;
            var filePath;
            if (typeof item === 'object') {
                filePath = item.path;
                contents = item.contents || '';
                linkTarget = item.linkTo;
            } else if (typeof item === 'string') {
                filePath = item;
                contents = '';
            }
            if (typeof filePath !== 'string' || filePath.length === 0) {
                throw new Error('file path not specified');
            }

            contents = contents || '';
            try {
                if (!!linkTarget) {
                    _fs.symlinkSync(linkTarget, filePath);
                } else {
                    _fs.writeFileSync(filePath, contents);
                }
            } catch (e) {
                // Eat the exception.
            }
        });
    }
1078817
function readDirSync (dir, allFiles = []) {
  const files = fs.readdirSync(dir).map(f => join(dir, f))
  allFiles.push(...files)
  files.forEach(f => {
    fs.statSync(f).isDirectory() && readDirSync(f, allFiles)
  })
  return allFiles
}