Wednesday, 10 May 2017

Node.js | callback is not defined

I'm new to Node.JS and I'm trying to understand callback. I was wondering what's wrong with my code. I was expecting that it will display all files without their extensions in the directory but all I got is undefined message.

'use strict';

const fs = require('fs');
const postsDirectory = './app/posts';

function listPosts(callback) {
    let posts = [];
    fs.readdir(postsDirectory, function(err, files) {
        if (err) {
            callback(err);
        } else {
            files.forEach(file => {
                posts.push(file.split('.').slice(0, -1).join('.'));
            });
            callback(posts);
        };
    });
};

console.log(listPosts());
process.exit(0)



via sedawkgrep

No comments:

Post a Comment