workshopper / learnyounode

Learn You The Node.js For Much Win! An intro to Node.js via a set of self-guided workshops.
Other
7.25k stars 1.84k forks source link

Make it Modular: Issue when using named imports for `fs` #700

Open reccanti opened 4 years ago

reccanti commented 4 years ago

Hello! I noticed a potential issue in the "Make it Modular" exercise. When importing readdir using a named import like this:

const { readdir }  = require("fs");
const { extname } = require("path");

module.exports = function filterFilesByExtension(directory, extension, callback) {
    function isExtension(file) {
        return extname(file) === "." + extension;
    }
    readdir(directory, (err, files) => {
        if (err) {
            return callback(err);
        }
        const matchingFiles = files.filter(isExtension)
        callback(null, matchingFiles);
    });
}

I get the following error:

 Your additional module file [mymodule.js] does not appear to pass back an
 error received from fs.readdir(). Use the following idiomatic Node.js
 pattern inside your callback to fs.readdir(): if (err) return
 callback(err)

 # FAIL Your solution to MAKE IT MODULAR didn't pass. Try again!

However, if I use default imports like this:

const fs  = require("fs");
const { extname } = require("path");

module.exports = function filterFilesByExtension(directory, extension, callback) {
    function isExtension(file) {
        return extname(file) === "." + extension;
    }
    fs.readdir(directory, (err, files) => {
        if (err) {
            return callback(err);
        }
        const matchingFiles = files.filter(isExtension)
        callback(null, matchingFiles);
    });
}

It verifies correctly. I think this may be due to how you're mocking fs.readdir.

Not sure what the more flexible fix would be, but I'd be happy to help if you point me in the right direction!

ccarruitero commented 4 years ago

Hi @reccanti , thanks for notice this.

In order to solve this, I think we can use a mocking library (like sinon) instead doing the mock manually.