When using figlet I am really struggling to output the text to the command line using the default example on https://www.npmjs.com/package/figlet.
I have a class and it has a method that once run should output some text to the command line.
My code looks like this:
/* eslint-disable no-console */
var figlet = require('figlet');
class Page {
async run () {
console.log('figlet start');
console.log(figlet);
//console.log(figlet.textSync('Hello World!', 'Standard'));
figlet('Hello World!', 'Standard', function(err, data) {
if (err) {
console.log('Something went wrong...');
console.dir(err);
return;
}
console.log(data);
});
console.log('figlet end');
process.exit(0);
}
}
module.exports = {
Page
};
The output from this is:
[Function: me] {
text: [Function (anonymous)],
textSync: [Function (anonymous)],
metadata: [Function (anonymous)],
defaults: [Function (anonymous)],
parseFont: [Function (anonymous)],
loadFont: [Function (anonymous)],
loadFontSync: [Function (anonymous)],
preloadFonts: [Function (anonymous)],
figFonts: {},
fonts: [Function (anonymous)],
fontsSync: [Function (anonymous)]
}
figlet end
If I uncomment the line //console.log(figlet.textSync('Hello World!', 'Standard'));
then is displays "Hello world!" twice.
I'm really scratching my head as to what it is I am doing wrong. I can run the examples in the figlet repo fine from my command line.
Perhaps I have fundamentally misunderstood something so it would be good to learn what that is.
CodePudding user response:
node.js is asynchronous, so process.exit(0);
runs before figlet
is finished, which shows in the output
if you comment out process.exit(0);
, the last output should be figlet's "hello world"
so the output actually ends within figlet
's callback, so you should move everything there:
/* eslint-disable no-console */
var figlet = require('figlet');
class Page {
async run () {
console.log('figlet start');
console.log(figlet);
//console.log(figlet.textSync('Hello World!', 'Standard'));
figlet('Hello World!', 'Standard', function(err, data) {
if (err) {
console.log('Something went wrong...');
console.dir(err);
return;
}
console.log(data);
console.log('figlet end');
process.exit(0);
});
}
}
module.exports = {
Page
};