0

This is a basic question, but I'm struggling to find the answer. I am trying to import a js file (located here: http://eloquentjavascript.net/code/ancestry.js) into my Cloud9 Nodejs IDE, but I don't know how to do it.

I have successfully imported the file into my library. However, I am unclear on what I am to do with the code added at the bottom of the file:

// `require(./path/to/ancestry.js)` will get you the array.
if (typeof module != "undefined" && module.exports)
  module.exports = ANCESTRY_FILE;

I tried adding it to the server.js file with no success.

Thanks in advance, josh

1
  • Did you try saving the file as is and instead call it inside another JS file, within the same directory, using var ancestry = require('./ancestry'); Commented Feb 2, 2016 at 17:45

1 Answer 1

1

The code at the bottom is usually to check whether CommonJS is enabled (basically, is it Node.js or browser). As long as you have the ancestry file in a folder, make another file inside the same folder, e.g: list-ancenstry.js and write into it:

var ancestry = require("./ancestry"); 
console.log(ancestry) //Logs the array
Sign up to request clarification or add additional context in comments.

4 Comments

Your suggestion worked. However, I cannot run the code in the immediate window (Javascript REPL). The following gets me a ReferenceError: var ancestry = JSON.parse(ANCESTRY_FILE)
NO, run it using require. Make sure you read up on module imports in Node.js. Btw, whats your setup? It doesn't sound like a generic Node.js setup.
If I type 'var ancestry = require("./ancestry");' in the immediate window, I get 'ReferenceError: require is not defined'. As far as my set-up is concerned, I'm afraid I don't know how to answer that question. This is new to me. What information are you looking for?
If require is undefined, it looks like your node setup needs some tweaking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.