简体   繁体   中英

Using a JS function to use the syntax of another? node.js

Probably titled this one badly, will try and explain a bit better.

Basically I've been trying to make a function:

var readlineSync = require('readline-sync');
function i(context) {
  readlineSync.question(context)
} 

var Username = i("Testing the prompt: ") 
console.log(Username)  

I find having to write readlineSync.question over and over again rather irritating, but running the code returns this:

Testing the prompt: Hello
undefined

Am I doing something wrong?

You're not returning anything from the function.

It should be:

function i(context) {
  return readlineSync.question(context)
} 

You could just do:

var i = readlineSync.question

// usage
i('Testing the prompt: ')

Creating an alias of the function

Or, if you are using an ES6 capable environment (Node 6 or Chrome):

import { question as i } from 'readline-sync'

// usage
i('Testing the prompt: ')

Which is the same of:

var i = require('readline-sync').question

// usage
i('Testing the prompt: ')

you forgot the return statement

function i(context){
 return readlineSync.question(context)
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM