节点模块无法识别为模块

Node module not recognize as module

我有一个文件,我认为它应该作为一个模块导入,但是当我尝试将它导入到我的主文件中时(参见 main.js),我收到以下错误:

 Error: Cannot find module 'sessionStore.js'

我确定文件位于正确的位置。任何想法还有什么可能导致这个?

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
};

您尝试过使用相对路径吗?如果它们在同一目录中,则

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

没有 .js

您收到的错误是因为节点无法在 node_modules 目录中找到您的 sessionStore 模块。

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

您可能想使用文件的相对路径。类似于: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.