简体   繁体   English

NodeJs require('../ file.js')问题

[英]NodeJs require('../file.js') issues

i am trying to build a nodeJs app with express, sequelize and and sqlite. 我正在尝试使用express,sequelize和and sqlite构建一个nodeJs应用程序。 So in my root directory i have a routers directory where i store '.js' files of express's routers. 因此,在我的根目录中,我有一个路由器目录,其中存储了Express路由器的.js文件。 And again in root directory i have a 'db.js' file. 再次在根目录中,我有一个“ db.js”文件。 The problem is, when i try to require "db.js" file from the routers folder's '.js' files. 问题是,当我尝试从路由器文件夹的“ .js”文件中请求“ db.js”文件时。 it says 它说

    Error: Cannot find module 'db.js'

I'm using require as in the example below 我在下面的示例中使用require

    db = require('../db.js');

Can someone help me find my mistake? 有人可以帮我找到我的错误吗? Thanks alot 非常感谢

Your current directory isn't what you think it is, so "../" is failing to go where you think it should. 您当前的目录不是您认为的那样,因此“ ../”无法转到您认为应该的位置。 Try something like this: 尝试这样的事情:

db = require('path').join(__dirname,'../db.js')

Here is the info on __dirname and path . 这是有关__dirnamepath的信息。

the root directory is where you start the app by calling node on that js file. 根目录是您通过在该js文件上调用node来启动应用程序的位置。

if the file is on the root of that file, you need to write 如果文件在该文件的根目录下,则需要编写

var db = require('./db'); // same file as yours.

using '../' will go to the parent folder and look there. 使用'../'将转到父文件夹并在其中查找。

using 'db' directly will look in the node_modules for the db module. 直接使用'db'将在db模块的node_modules中查找。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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