简体   繁体   中英

No such file or directory when exporting function from another file

src/test.js

module.exports.test = function() {
    const { readFileSync } = require('fs');
    console.log(readFileSync('test.txt', 'utf8').toString())
}

index.js

const { test } = require('./src/test.js');
test();

Which results in No such file or directory. Does module.exports or exports not work when requiring files in another directory?

When you do something like this:

readFileSync('test.txt', 'utf8')

that attempts to read test.txt from the current working directory. That current working directory is determined by how the main program got started and what the current working directory was when the program was launched. It will have nothing at all to do with the directory your src/test.js module is in.

So, if test.txt is inside the same directory as your src/test.js and you want to read it from there, then you need to manually build a path that references your module's directory. To do that, you can use __dirname which is a special variable set for each module that points to the directory the module is in.

In this case, you can do this:

const path = require('path');

module.exports.test = function() {
    const { readFileSync } = require('fs');
    console.log(readFileSync(path.join(__dirname, 'test.txt'), 'utf8').toString())
}

And, that will reliably read test.txt from your module's directory.

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