Danny Danny - 3 months ago 10x
Node.js Question

Issue with Importing Files in NodeJS Application`

I'm attempting to create a simple API using NodeJS and Express, but am running into issues with importing external javascript code into my application. I have set up the following basic test code:

var express = require("express");
var bodyParser = require('body-parser');
var fovea = require('../fovea.js');
var app = express();

app.use(bodyParser.urlencoded({ extended: true }));

var port = process.env.PORT || 8000;

var router = express.Router();

router.get('/', function(req, res) {
res.json({ message: "Welcome to the Fovea API" });
var lay = fovea.Layer2D("red", "layer");

The fovea.js file is a js file containing two classes which I have saved in the parent directory. When I send a GET request to the root address, I get the following error being caused by my attempt to construct the Layer2D object:

TypeError: Object #<Object> has no method 'Layer2D'
at Object.app.post.layer [as handle] (/home/daniel/Documents/coding/retina/retina/web/api/server.js:15:18)
at next_layer (/home/daniel/Documents/coding/retina/retina/web/api/node_modules/express/lib/router/route.js:103:13)
at Route.dispatch (/home/daniel/Documents/coding/retina/retina/web/api/node_modules/express/lib/router/route.js:107:5)
at c (/home/daniel/Documents/coding/retina/retina/web/api/node_modules/express/lib/router/index.js:195:24)
at Function.proto.process_params (/home/daniel/Documents/coding/retina/retina/web/api/node_modules/express/lib/router/index.js:251:12)
at next (/home/daniel/Documents/coding/retina/retina/web/api/node_modules/express/lib/router/index.js:189:19)
at Function.proto.handle (/home/daniel/Documents/coding/retina/retina/web/api/node_modules/express/lib/router/index.js:234:5)
at Layer.router (/home/daniel/Documents/coding/retina/retina/web/api/node_modules/express/lib/router/index.js:23:12)
at trim_prefix (/home/daniel/Documents/coding/retina/retina/web/api/node_modules/express/lib/router/index.js:226:17)
at c (/home/daniel/Documents/coding/retina/retina/web/api/node_modules/express/lib/router/index.js:198:9)

Here is the relevant class constructor from the fovea.js file:

function Layer2D(name, graphDiv){
this.name = name;
this.graphDiv = graphDiv;
this.traces = [];
this.hlines = [];
this.vlines = [];
this.bounds = [];
this.visible = true;

I'm using NodeJS v0.10.25, installed from the Ubuntu 14.04 apt repository. It seems that the fovea.js file is not being properly imported, but I can't figure out why that would be the case. Any help would be greatly appreciated.


So, the fovea.js file should look like:

// web/fovea.js
function Layer2D (name, graphDiv) {
   this.name = name;
   // ...

exports.Layer2D = Layer2D;

As you're defining an object, you need to use the new keyword to instantiate a layer:

// web/api/server.js

var fovea = require('../fovea.js');

// rest of the code

var lay = new fovea.Layer2D("red", "layer");

// >> "red"