3

I am trying to use Node.js with Amazon AWS and when I try to declare an aws instance I keep getting returned undefined. Also when I try to require a common module such as http, terminal also returns undefined. This occurs when I try to execute my actual script.

Terminal Snippet:

User$ node

> var aws=require('aws-sdk')
    undefined

> var web =require('http')
undefined
Bruno Reis
  • 34,789
  • 11
  • 109
  • 148
Mohammed B
  • 193
  • 3
  • 14

1 Answers1

11

What you are seeing is not the return value of require(...), simply because that's not what you have typed.

You are observing the result of the statement, var aws = require('aws-sdk'). And that statement, a variable declaration with an assignment, has an "undefined value". If you inspect what has been stored in the aws variable, you'll see that it is not undefined, it contains the module returned by the require(...) call.

Try this:

  • start node
  • type var x = 2

You'll also see undefined. And you know that "2" is definitely not "undefined".

Now, try this:

  • start node
  • type require('aws-sdk') (or any other module, such as http; note that this is just requiring the module, not assigning it to any variable)

You'll see the module being printed in the REPL.

Finally, try this:

  • start node
  • type var aws = require('aws-sdk')
  • the type aws

This will print the value of the aws variable into the REPL. And that value is whatever has been returned by the require(...) call. And you'll see that it's definitely not "undefined".

This is the precisely expected behavior of Node.js in whatever platform (i.e., what you are observing is completely unrelated to the fact that you are running Node on AWS; you could run it on your laptop, whatever OS you have, and you'd see the exact same behavior).

Bruno Reis
  • 34,789
  • 11
  • 109
  • 148
  • I'm having a similar problem (I think). I require an external library in my Node server `var jwt = require("jsonwebtoken");`. But when I try to access `jwt`, it says it's not defined. Perhaps has to do with `"use strict;"` affecting external functions, but any thoughts on a workaround? – Qasim Nov 21 '17 at 05:28
  • @Qasim - based on your very short description, it seems like you have a different problem than the OP. I'd suggest that you open a specific question with your problem, including details and some code that reproduces the problem. – Bruno Reis Nov 21 '17 at 06:00
  • Thanks @BrunoReis, I just did (and included my code) https://stackoverflow.com/questions/47406325/how-do-i-access-libraries-im-adding-via-require-in-my-node-koa-server – Qasim Nov 21 '17 at 06:11