简体   繁体   中英

Cannot find module - relative paths

I wrote a very simple local module to manage a few lines of localized text. It uses node's require to load the language files, but I'm having trouble with paths, most likely. I'm getting the Cannot find module error.

File structure

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

Relevant module code

Should require the file if it is not already loaded.

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

if(!_locales[lang]){
    _locales[lang] = require(join(_config.path, lang));
}

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

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 res.locals , however, I'm seeing Cannot find module 'locale/en' error.

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


The module is called in index.coffee .
App is launched using init.js , which contains the following:

require('coffee-script/register');
require('./index');

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM