Wednesday, March 4, 2020

How to fix ReferenceError: function is not defined Node.js?

I just encountered an issue that function is not defined. when i checked my code. the function did exist in the script file.

ReferenceError: fullUrl is not defined
    at Command.program.command.description.action (/mnt/c/node/esclu/index.js:22:17)
    at Command.listener (/mnt/c/node/esclu/node_modules/commander/index.js:301:8)
    at Command.emit (events.js:198:13)
    at Command.parseArgs (/mnt/c/node/esclu/node_modules/commander/index.js:615:12)
    at Command.parse (/mnt/c/node/esclu/node_modules/commander/index.js:458:21)
    at Object.<anonymous> (/mnt/c/node/esclu/index.js:25:9)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)


the root cause of this issue is that the order of the defined function is really matter in Node.js

i had to move this function definition to the location after the require lines.


'use strict';

const fs=require('fs');
const request=require('request');
const program =require('commander');
const pkg=require('./package.json');

const fullUrl=(path='')=>{
    let url=`http://${program.host}:${program.port}`;
    if(program.index){
        url +=program.index +'/';
        if(program.type){
            url +=program.type +'/';
        }
    }
    return urlpath.replace(/^\/*/'');
}

program
.version(pkg.version)
.description(pkg.description)
.usage('[options] <commander> [...]')
.option('-o, --host <hostname>','hostname [hostname]','localhost')
.option('-p, --port <number>','port number [9200]''9200')
.option('-j, --json','format output as json')
.option('-i, --index <name>','which index to use')
.option('-t, --type <name>''default type for bulk opertions');

program
.command('url [path]')
.description('generate the url for the options adn apth (default is /)')
.action((path='/')=>{
    console.log(fullUrl(path));
});

program.parse(process.argv);

if(!program.args.filter(arg=> typeof arg=='object').length){
    program.help();
}



No comments:

Post a Comment