vendredi 23 août 2019

How to expand fancy ES6 syntax into human readable code?

I was 'thrown' this:

const { readdir, readFile, stat } = require ("fs").promises
const { basename, join } = require ("path")

const dir2obj = async (path = ".") =>
    (await stat (path)) .isFile ()
        ? { [basename (path)]: await readFile (path) }
        : Promise
                .all
                    ( (await readdir (path))
                            .map
                                ( p => 
                                        dir2obj (join (path, p))
                                            .then (obj => ({ [p]: obj }))
                                )
                    )
                .then (results => Object.assign(...results))

// run it
dir2obj ("path/to/somewhere")
    .then (console.log, console.error)

And it sort of do what I need. My problem is, that I need to be able to manipulate the incoming and outgoing data ... and that I cannot do with the above code, as it is super compact – basically just a ternary operator.

Now, I've spend a few hours trying to 'convert' this into something human readable – yeah, I know the trend is to make code absolutely obscure, but nevertheless.

My issue is especially the initial .isFile() which is chained on to the async call wich return a stat.

Now, HOW would I turn this into something where I, instead of an ternary operator, would get the classic if / else statement in order to be able to manipulate the date in and out?

Basically something like this:

let files = fs.readdirSync( dir );

files.forEach( filename => {
    fs.stat( dir + '/' + filename, function ( err, stats ) {
        if ( stats.isFile() ) {

        } else if ( stats.isDirectory() ) {

        }
    });
});

return files;

Aucun commentaire:

Enregistrer un commentaire