NodeJS package outputting empty string

Issue

I’m trying to create my own NodeJS package that uses the chalk to output colored strings, but i’m getting empty string as output( when i run node test.js in terminal ) I tried searching online but couldn’t find any reason for this. Does anyone have an idea what could be causing this error?

index.js file

import chalk from 'chalk';
import pkg from 'koa/lib/request';
const { charset } = pkg;
const fontColors = ['red','green','yellow','blue','magenta','cyan',];
export const colourfulLog = (string) => {
    const colorString = string.split(' ')
        .map(word => {
            const randclrindex = Math.floor(Math.random() * fontColors.length);
            const randColor = fontColors[randclrindex];
            return chalk[randColor][word];
        })
        .join(' ');
    console.log(colorString);
}

test.js file

import { colourfulLog } from './index.js';
colourfulLog(' Test the colorful log package');

package.json file

{
  "name": "colorful-log-ax",
  "version": "1.0.0",
  "description": "first package",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },

  "author": "AT",
  "license": "ISC",
  "dependencies": {
    "chalk": "^5.0.1"
  },
  "type": "module"
  
}

Solution

There is an error in your index.js file:

    return chalk[randColor][word];

You are using square brackets to dynamically specify a method: chalk[randColor] is like saying chalk.randColor, then you have to apply it to word like this:

    return chalk[randColor](word);

Answered By – arftex

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.