0

I have file, which I believe should be imported as a module, but it when I try to import into my main file (see main.js), I get the follow error:

 Error: Cannot find module 'sessionStore.js'

I'm made sure that the file in in the correct location. Any ideas what else could cause this?

main.js

var express = require('express');
var bodyParser = require('body-parser');
var util = require('util');
var toMarkdown = require('to-markdown');
var jsdiff = require('diff');
var marked = require('marked');
var pg = require('pg');
//need to get sessions to work and use server credentials instead of password
var sessionStore = require('sessionStore.js');
var PodioJS = require('podio-js').api;
var podio = new PodioJS({authType: 'password', clientId: "xxx", clientSecret: "xxx" },{sessionStore:sessionStore});

sessionStore.js

var fs = require('fs');
var path = require('path');

function get(authType, callback) {
  var fileName = path.join(__dirname, 'tmp/' + authType + '.json');
  var podioOAuth = fs.readFile(fileName, 'utf8', function(err, data) {

    // Throw error, unless it's file-not-found
    if (err && err.errno !== 2) {
        throw new Error('Reading from the sessionStore failed');
    } else if (data.length > 0) {
      callback(JSON.parse(data));
    } else {
      callback();
    }
  });
}

function set(podioOAuth, authType, callback) {
  var fileName = path.join(__dirname, 'tmp/' + authType + '.json');

  if (/server|client|password/.test(authType) === false) {
    throw new Error('Invalid authType');
  }

  fs.writeFile(fileName, JSON.stringify(podioOAuth), 'utf8', function(err) {
    if (err) {
      throw new Error('Writing in the sessionStore failed');
    }

    if (typeof callback === 'function') {
      callback();
    }
  });
}

module.exports = {
  get: get,
  set: set
};
Niels Sønderbæk
  • 3,487
  • 4
  • 30
  • 43

2 Answers2

3

have you tried using relative paths? If they're in the same directory, then

var sessionStore = require('./sessionStore');

without the .js

user156213
  • 736
  • 4
  • 12
3

The error you're getting is because node can't find your sessionStore module in the node_modules directory.

If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then node starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.

https://nodejs.org/api/modules.html#modules_file_modules

You probably want to use a relative path to your file. Something like: require('./sessionStore')

A module prefixed with '/' is an absolute path to the file. For example, require('/home/marco/foo.js') will load the file at /home/marco/foo.js.

A module prefixed with './' is relative to the file calling require(). That is, circle.js must be in the same directory as foo.js for require('./circle') to find it.

Community
  • 1
  • 1
Robbie
  • 18,750
  • 4
  • 41
  • 45