简体   繁体   English

为什么这段代码显示找不到模块错误?

[英]why is this code showing cannot find module error?

inside localbase.js...在 localbase.js 里面...

const fs = require("fs");

if(!fs.existsSync(__dirname + "/localbase.json")) 
  fs.writeFileSync("./localbase.json", "{}");

let database = require("./localbase.json");

This above code is showing this error Error: Cannot find module './localbase.json' .上面的代码显示了这个错误Error: Cannot find module './localbase.json'

The file is imported in server.js as follows.该文件在server.js中导入如下。

const lb = require('./db/localbase.js');

my directory structure (apology if my tree looks bad)...我的目录结构(如果我的树看起来不好,请道歉)......

|- db
+--- localbase.js
|- node_modules
|- public
server.js
package.json

But if I put the localbase.js where the server.js is then it's perfectly fine.但是,如果我将 localbase.js 放在 server.js 所在的位置,那就完全没问题了。

so the fix is real simple...所以修复真的很简单......

const fs = require("fs");

if(!fs.existsSync(__dirname + "/localbase.json")) 
  fs.writeFileSync(__dirname + "/localbase.json", "{}");

let database = require(__dirname + "/localbase.json");

So basically what I did is I imported relative the root directory(where the node_modules is) which was causing that error.所以基本上我所做的是我导入了导致该错误的相对根目录(node_modules 所在的位置)。

I thought using require('./localbase.json') would choose the directory relative to server.js but it won't.我认为使用require('./localbase.json')会选择相对于server.js的目录,但不会。

So what I learnt is require() uses paths relative to root directory.所以我学到的是require()使用相对于根目录的路径。

Which means I have to use __dirname to import modules inside of sub-directories.这意味着我必须使用__dirname在子目录中导入模块。

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

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