dagda1 dagda1 - 6 days ago 4
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');

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

console.dir(config);

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

console.log(url);

yield Promise.resolve(url);
})


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

Answer

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');