Bali Vinayak
Bali Vinayak

Reputation: 289

How to invoke JS function from one file to another in node.js?

I am new to JS and trying to break the code into multiple modules. I am running nodejs and I am puzzled here on why is it complaining about pathChecker not defined. Any ideas on it?

<

const http = require('http');
const parseUrl = require('parseurl');
const path = require('path');


http.createServer( function (req, res)
{
    try
    {

        // this is library function
        var pathName = decodeURIComponent(parseUrl(req));

        // create a literal validateFile to validate the path
        var validateFile = new pathChecker(pathName);

        // This is an engine to validate the path problems related to security, existence etc.
        validateFile.pathCheck();

        if(validateFile.error === true) {
            res.statusCode = validateFile.statusCode;
            res.end(validateFile.ErrorMsg);

            return;
        }

    }
    catch(err)
    {
        res.statusCode = err.status || 500;
        res.end(err.message);
    }

}).listen(4000);

I have another file called

errorHandler.js

function pathChecker(path)
{
    this.error = true;
    this.path = path;
    this.statusCode = 500;
    this.ErrorMsg = "Internal Server Error";
    this.pathCheck = function()
    {
        if(!path)
        {
            this.statusCode = 400;
            this.ErrorMsg = 'path required';
            this.error = true;
        }
        else{
            this.statusCode = 200;
            this.ErrorMsg = undefined;
            this.error = false;
        }
    }
};

On running this, I get the output

pathChecker is not defined

Upvotes: 2

Views: 104

Answers (2)

Greg Hornby
Greg Hornby

Reputation: 7798

You need to export the function in your errorHandler.js file.

function pathChecker(path) {
  ...
}
module.exports = pathChecker;

then import it into your main file with

const pathChecker = require("./errorHandler")

Upvotes: 0

Goblinlord
Goblinlord

Reputation: 3390

You need to export and import the file as a module. You do this like this:

// File A.js
function A() {
}

module.exports = A;

// File B.js
var A = require("./A");
A();

Note that the name A is arbitrary on the import and you can name whatever you want. You can also export an object with functions on it instead of a single function and then when importing you can get properties off of it. This way you can export more than one function or value from a single file.

Upvotes: 2

Related Questions