ROAL ROAL - 1 year ago 159
Javascript Question

Cannot find module - relative paths

I wrote a very simple local module to manage a few lines of localized text.
It uses node's

to load the language files, but I'm having trouble with paths, most likely.
I'm getting the
Cannot find module

File structure

+-- local_modules
| +-- lang
| | +-- package.json
| | +-- index.js
+-- locale
| +-- en.js
| +--
+-- init.js
+-- package.json

Relevant module code

the file if it is not already loaded.

join = require('path').join;
_config.path = './locale';
lang = 'en';
_locales = {};

_locales[lang] = require(join(_config.path, lang));

Every file in the
directory is a typical Node.js module, for example

module.exports = {
test: 'Hello World!'

The local module exports a
function(req, res, next){}
, which is used as Express middleware and is supposed
to attach the required object with localized strings onto
, however, I'm seeing
Cannot find module 'locale/en'

I've tried to manually add the
extensions (but that shouldn't be neccessary as far as I know).
I have also tried different variations on the path, such as

The module is called in

App is launched using
, which contains the following:


Maybe it's just that the module is a
(and the module itself doesn't have CoffeeScript as a dependency) so it can not load a
file? Although CoffeeScript should be registered globally, or am I wrong? Either way, it doesn't work with the
file either, so I guess it has something to do with paths.

Answer Source

path.join() also normalizes the created path, which (probably) means the ./ part was always removed, and what remained was a relative path.

Instead, when path.resolve() is used, it creates an absolute path, which is what is needed in this case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download