MGD
MGD

Reputation: 783

TypeError: undefined is not a function Node JS

I am newbie to JavaScript, I am running a very basic code but having trouble with it. The code is as follows

MyService.js

var http = require('http');
var express = require('express');
var app = express();

var gpioControl = require('./GPIOController');

app.get('/pressUp/', function (req, res){
    console.log("Pressed Up");
    gpioControl.upButtonPress();
});

app.get('/pressDown/', function (req, res){

    console.log("Pressed Down");
    gpioControl.downButtonPress();
});

app.listen(3000);

console.log("The server is running on port 3000");

GPIOController.js

var upButtonPress = function ()
{
    console.log ("UP Button has been pressed!");
}

var downButtonPress = function()
{
    console.log ("Down Button has been pressed!");
}

The Error I get is below :

TypeError: undefined is not a function
   at C:\Users\mehroz\Desktop\Rasberry Pi Automation\MyService.js:11:14
   at Layer.handle [as handle_request] (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\layer.js:82:5)
   at next (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\route.js:110:13)
   at Route.dispatch (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\route.js:91:3)
   at Layer.handle [as handle_request] (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\layer.js:82:5)
   at C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\index.js:267:22
   at Function.proto.process_params (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\index.js:321:12)
   at next (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\index.js:261:10)
   at expressInit (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\middleware\init.js:23:5)
   at Layer.handle [as handle_request] (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\layer.js:82:5) 

Upvotes: 0

Views: 682

Answers (1)

papiro
papiro

Reputation: 2365

if GPIOController.js is a node module (which it looks like it is), it needs to use the CommonJS pattern. That being said, you should change the var declarations in GPIOController to be exports.your-function-name-here declarations.

So, var upButtonPress = function(){} would become

exports.upButtonPress = function(){}

It would then work as you are using it in MyService.js.

Upvotes: 1

Related Questions