0

I am very new to node js and javascript execution in node js. I am trying to execute one small script in node js with arguments, I want to pass message and user name in function written in myTest.js

myTest(message, user);

function myTest(message, user) {
    console.log(message + ": "+ user);
}

I am getting below error:

(function (exports, require, module, __filename, __dirname) { myTest(message, user);
                                                                 ^

ReferenceError: message is not defined
    at Object.<anonymous> (C:\Users\kp250041\Desktop\ProgramFiles\mytest.js:1:70)
    at Module._compile (internal/modules/cjs/loader.js:688:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
    at startup (internal/bootstrap/node.js:285:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)

Please advise.

ioseph
  • 1,887
  • 20
  • 25
snowcoder
  • 481
  • 1
  • 9
  • 23
  • When you call the myTest function, are you still inside the myTest.js when you call it? or in another file? – John Nov 07 '18 at 23:03
  • 1
    This error has nothing to do with node.js (https://jsfiddle.net/khrismuc/4j3bxhrg/) and you aren't even trying to access any command line arguments. –  Nov 07 '18 at 23:05
  • 1
    It sounds like your asking how to execute command line arguments in Node Js. Here is a post to look at if that's the case: https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program – David Yates Nov 07 '18 at 23:17

1 Answers1

5

So what this error is telling you is that you are referencing the variable message which has not been defined. In order to define both message and user you are going to need to fetch those values from the command line arguments.

In order to do this we are going to access them via process.argv. Assuming that you are passing message first and user second then the resulting code would look something like this.

// The first argument is the node executable
// The second is the script file name
let message = process.argv[2],
    user = process.argv[3];

function myTest(message, user) {
    console.log(message + ": "+ user);
}

myTest(message, user);

For more information on command line arguments in Node.js please see this post.