node.js require 找不到自定义模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16652620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:32:46  来源:igfitidea点击:

node.js require cannot find custom module

javascriptmacosnode.jsrequire

提问by thgie

Here is the project structure:

这是项目结构:

/
  app.js
  package.json
  /node_modules
  /app
    config.json
    /frontend
      assets and html tpls
    /modules
      couch.js
      raeume.js
      users.js

I require config.json, raeume.js and users.js from app.js and it all works fine.

我需要来自 app.js 的 config.json、raeume.js 和 users.js,并且一切正常。

var config   = require('./app/config');
var raeume   = require('./app/modules/raeume');
var users    = require('./app/modules/users');

Then I require config.json and couch.js from user.js the same way and it won't find anything.

然后我以同样的方式从 user.js 中要求 config.json 和 couch.js,它不会找到任何东西。

var couch     = require('./app/modules/couch');
var config    = require('./app/config');

I guess it should find it. After some research I saw a diverse landscape of problems inclusive how node is compiled. Thus included: I work on osx 10.8 with node v0.10.7.

我想它应该找到它。经过一些研究,我看到了各种各样的问题,包括 node 是如何编译的。因此包括:我使用节点 v0.10.7 在 osx 10.8 上工作。

回答by Alberto Zaccagni

The path is relative to the directory in which you are requireing the files, so it should be something like:

该路径是相对于您正在放置require文件的目录,因此它应该类似于:

var couch = require('./couch');
var config = require('../config');

A bit of clarification, if you write

有点澄清,如果你写

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

you are trying to requirethe couch module which resides in the current directory, if you write

你正在尝试require驻留在当前目录中的沙发模块,如果你写

var couch = require('couch');

you are trying to requirethe couch module installed via npm.

您正在尝试require通过npm.

回答by Dory Zidon

Here is how you do it :

这是你如何做到的:

var users    = require('./../modules/users');

回答by Nghiep Ngo

It must be:

肯定是:

var config = require(../../app/config)

var couch = require(./couch) (same directory)