Javascript – Node.js require() returns undefined always

javascriptnode.js

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

Best Answer

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).