简体   繁体   中英

node.js can't find module from relative path

I have two simple files in node.js and want to export two classes from one file and import them in the other. I'm using:

module.exports = {TrigInter, Hilbert};

Now, if I call require, it only works with the absolute file path:

const lib = require("/Users/username/documents/atom/project_folder/lib.js");

and not with the relative file path:

const lib = require("./lib.js");

eventhough the two files are both located in the "project_folder". I'm pretty sure, I tried the exact same thing before and it worked with the relative path. I don't see what I'm doing wrong. What am I missing?

Absolute path is not best practice to use, instead you can use path join method like

const path = require('path');
let your_file_path = path.resolve(__dirname, '/lib.js');

https://www.digitalocean.com/community/tutorials/nodejs-how-to-use__dirname

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