I’m trying to import a file in server.js of a meteor project on Linux. For example:
var temp = require('/home/HaveAGitGat/Documents/test.js');
I get the following error:
Error: Cannot find module '/home/HaveAGitGat/Documents/test.js'
The confusing thing is this works fine on Windows using meteor. It also works fine on Linux when running pure nodejs files without meteor.
Any ideas on a resolution?
Welcome to the forums!
I’m surprised that it works in Windows, as Meteor has special semantics where a leading /
refers to the project root.
This is primarily because the Meteor bundler collects and transpiles the dependency graph into a temporary build, so accessing files outside the application directory doesn’t make a lot of sense.
You could theoretically get around this by reading the file’s contents with fs
and eval
-ing it
Why do you want to require a file outside the application anyway?
Just gave this a quick test on my Mac and (as expected) could not require modules outside the application.
I did get the fs
+ eval
approach to work:
const hwSource = fs.readFileSync('/Users/fredstark/helloworld.js', 'utf8');
const hwFunc = new Function('module', hwSource);
const hwModule = { exports: {} };
hwFunc(hwModule)
const hw = hwModule.exports;
console.log(hw('World'));
Using a very rough approximation of common-js module loading
1 Like
Thanks for the idea! I’ll give it a go. The issue is I’m trying to read user-configurable data from the user’s Documents folder for a desktop application so I’d like to do it this way rather than have the user dig into all the sub-folders of the application to modify things.
That makes sense!
I’d load with fs
and parse. Which is much easier if the config is json/yaml/toml/etc instead of actual javascript, but it can be done
This worked perfectly on Windows and Ubuntu, thanks!