dagda1 dagda1 - 1 year ago 89
Node.js Question

yield with promisified readFile returning undefined

I have the following helper method:

module.exports.rootUrl = co(function* () {
const jsonPath = path.resolve(process.cwd(), './server/config.json');

let config;
try {
const readFile = Promise.promisify(fs.readFile);
const config = yield readFile(jsonPath, 'utf-8');
} catch (err) {
yield Promise.reject(err);


const url = `http://${config.host}:${config.port}/${config.restApiRoot}`;


yield Promise.resolve(url);

The problem is that the call to
yield. readFile(jsonPath, 'utf-8')
is returning undefined.

Answer Source

The problem is that you're redeclaring config (as a block-scoped const) inside the try, which means that it's out of scope when you console.dir it, and you end up logging the (undefined) config that you declared with let.

This should work:

config = yield readFile(jsonPath, 'utf-8');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download