2

I am working on a CLI with typescript and using enquirer to do so. https://www.npmjs.com/package/enquirer

I have a JSON present.

const a = {
   name: 'Mohan',
   age: '5',
};

After that I start the Enquirer prompt.

Enquirer.prompt({
    name: 'inputVal',
    type: 'input',
    message: 'Create a Text',
  }).then(async response => {
    const output: string = (response as any).inputVal;
    console.log(output);
  });

This prompts for the value and I am trying to write this as the answer

${a.name} has age ${a.age}

This prints on console the following

${a.name} has age ${a.age}

What I want is for console.log to resolve this as

Mohan has age 5

I have tried eval as well but it did not work. Does anyone know how can we do this?

palaѕн
  • 72,112
  • 17
  • 116
  • 136
Prakhar
  • 530
  • 10
  • 24

2 Answers2

0

You have to convert a string to a template string first

const a = {
  name: 'Mohan',
  age: '5',
};
const string = "${a.name} has age ${a.age}";
const templateString = eval('`' + string + '`');
console.log(templateString);

Or you can try this without eval().

Full example:

const { prompt } = require("enquirer");

const a = {
  name: "Mohan",
  age: "5",
};

prompt({
  name: "inputVal",
  type: "input",
  message: "Create a Text",
}).then(async (response) => {
  const output = response.inputVal;
  const templateString = eval('`' + output + '`');
  console.log(templateString);
});

Input:

${a.name} has age ${a.age}

Produces this output:

$ node test.js
√ Create a Text · ${a.name} has age ${a.age}
Mohan has age 5
Maxim Mazurok
  • 3,856
  • 2
  • 22
  • 37
0

as i see,input is a json and you expect output is ${a.name} has age ${a.age} ?

try this?

Enquirer.prompt({
    name: 'inputVal',
    type: 'input',
    message: 'Create a Text'
}).then(async response => {
    // when you input json string  {"name":"Mohan","age":"5"}
    let a = JSON.parse(response)
    console.log(`${a.name} has age ${a.age}`);
});

link to Enquirer api link

emm,I am New contributor.if there are some wrong can reply me.thanks

Jing Jiang
  • 121
  • 5