Cannot find module XYZ - node.js

I know this problem has been submitted endless times but even after browsing through X questions and possible solutions this error still remains.
I have a file called tournament.js in the directory modules. tournament.js requires model.js which resides in the exact same directory. The structure is the following:
app/
modules/
model.js
tournament.js
tournament.js looks like:
const Model = require('./model');
class Tournament extends Model {
constructor() {
super();
}
static create() {
}
}
Even WebStorm says the path in require() is correct but my console still says: Uncaught Error: Cannot find module './model'
What am I missing?
Edit: I'm using Node v6.4.0 and Electron v1.4.15

Okay #adelphus gave me the correct hint. I outputted the path with console.log(__dirname) and it was not what I expected: Yes, I have been in the wrong path, because I thought the relative path require() takes is the one relative to the file I am currently working in (which was the tournament.js) and this is not the case.
Instead require() takes the path relative from the app root which in this case was ./app/models/model.js

Related

required module in node.js is always undefined

Currently experiencing something that is absolutely baffling. I am requiring the 'qrcode' module which I installed via npm (npm --save install qrcode).
const {
QRCode
} = require('qrcode');
The module is listed in my package.json and does exist in node_modules. However, this is absolutely always 'undefined'. When hovering over the string in the require statement I see that it is some how referencing a node_modules directory in my local/AppData directory which I'm assuming is the global directory for modules. Using this path always results in 'undefined'. I then tried switching the path to reference the local node_modules qrcode and still 'undefined'. I've read everything here https://www.npmjs.com/package/qrcode but doesn't help with the issue I'm seeing and there appears to be not a single conversation on google about this.
TypeError: Cannot read property 'toDataURL' of undefined
When using the 'qrcode' string it is using something in the #types folder which I thought was for ES6 which I am not using. No idea how to proceed nothing adds up here, any help greatly appreciated!
Node.js example from npm package page(if only it were this easy)
var QRCode = require('qrcode')
QRCode.toDataURL('I am a pony!', function (err, url) {
console.log(url)
})
When you do this:
const {
QRCode
} = require('qrcode');
You are expecting a QRCode property on the object that the module exports. This is called object destructing assignment in ES6. It is shorthand for and equivalent to this:
const QRCode = require('qrcode').QRCode;
And, since the object the module exports does NOT have a .QRCode property, you get nothing but undefined.
Instead, the top level object it exports is the QRCode object so you need to do this:
const QRCode = require('qrcode');
If you wanted a specific property that it was exporting, you could then do something like this:
const { toDataURL } = require('qrcode');

How to use multiple compiled ts files in a node module?

Currently I am trying to use TypeScript to create JavaScript-Files which are then required in a index.js file. I am using VS 2015 Update 3 with node.js tools 1.2 RC. Sadly it is not working like I thought it would.
To begin with here is my initial idea:
I have a node module (to be precise, it is a deployd module http://docs.deployd.com/docs/using-modules/). This module is handling payment providers like paypal or stripe. Now I want to use TypeScript to write interfaces, classes and use types to make it easier to add new payment providers. The old .js files should still be there and used. I want to migrate step by step and use the self-written and compiled .js files together. So I thought I can create .ts files, write my code, save, let VS compile to js and require the compiled js file in another js file. Okay, that is my idea... Now the problem
I have a PaymentProvider.ts file which looks like this
import IPaymentProvider = require("./IPaymentProvider.ts"); // Interface, can't be realized in JavaScript, just TypeScript
export abstract class PaymentProvider implements IPaymentProvider.IPaymentProvider
{
providerName: string;
productInternalId: number;
constructor(providerName : string)
{
this.providerName = providerName;
}
//... some methods
};
The other file is PaypalPaymentProvider.ts
import PaymentProvider = require("./PaymentProvider.ts");
export class PaypalPaymentProvider extends PaymentProvider.PaymentProvider
{
constructor()
{
super("paypal");
}
// more methods
}
VS 2015 doesn't show any errors. The js and .js.map files are generated. Now I thought I could require the files and that's it. I tried to use the PaypalPaymentProvider.js like this const PaypalPaymentProvider = require("./lib/payment-provider/PaypalPaymentProvider.js"); (yes, it is located there) but it's not working. When starting the index.js via node I get the following error:
...\Path\PaymentProvider.ts:1 (function (exports, require, module, __filename, __dirname) { import IPaymentProvider = require("./IPaymentProvider.ts"); Unexpected token import....
I find it strange that this is the error, because JavaScript doesnt't have Interfaces. The compiled IPaymentProvider.js is empty.
Also I thought that TypeScript is mainly for development and the compiled JavaScript for production. So why it is requiring a ts-file? I thought imports in typescript will be converted to require of the compiled js-file?
Do I need to require all compiled js files and not only the one I currently try to use? (I don't think so...)
To be honest, I think the main problem is that I am new to TypeScript and make something wrong from the very beginning.
Any help/advice? Thanks!
I have the solution... Thanks to Paelo's links I was able to see that I need to omit the file ending! So the really simple solution was to write
import IPaymentProvider = require("./IPaymentProvider");
instead of
import IPaymentProvider = require("./IPaymentProvider.ts");
When I changed that in every ts file it worked perfectly!

Using node require with Electron and Webpack

I am building a project with Electron, and using Webpack to build the (Angular 2) render process app.
In this app, I need to dynamically require some files at run-time which do not exist at build-time. The code looks something like this:
require("fs").readdirSync(this.path).forEach(file => {
let myModule = require(path.join(this.path, file));
// do stuff with myModule
});
The problem is that the Webpack compiler will convert the require() call to its own __webpack_require__() and at run-time, it will look in its own internal module registry for the dynamic "myModule" file, and of course will not find it.
I have tried using the "externals" config option, but since this is a dynamic require, it doesn't seem to be processed by "externals".
Anyone else had success in solving this problem?
As suggested in a comment to my question by #jantimon, the solution is to use global.require:
require("fs").readdirSync(this.path).forEach(file => {
let myModule = global.require(path.join(this.path, file));
// do stuff with myModule
});
I came across this article and for some other reason the author needs node modules which gets not transpiled by webpack. He suggested to use
new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$"))
in the webpack.config.js file. This should prevent to transpile the module fs and ipc so it can be used (required) in code.
I am not really sure if this hits also your problem but it might help.
The original article for more context can be found here: https://medium.com/#Agro/developing-desktop-applications-with-electron-and-react-40d117d97564#.927tyjq0y

get path of the file the module is being called from?

Let's say I have a node.js module
module.exports = function () {
console.log(__filename);
}
And in the main file I call it like
var x = require('path/to/module');
x();
That gives me the path to the module file. For example if I stored the module at ~/project-root/lib/mod.js and the main.js file lies at ~/project-root/main.js, that setup gives me the output:
~/project-root/lib/mod.js
I want to use something in place of __filename in the module that gives me to location of of the file from which it was called from. (e.g. the output would be ~/project-root/main.js instead, in this example).
The module can be located anywhere. So using path to adjust for only this example would fail in other scenarios (for example if module is stored in ~/project-root/node_modules/ or the global node.js modules directory.
I have a feeling it's something fairly trivial and I'm overlooking something. But I haven't found a solution from anything Google has yielded during an hour long search. Maybe I'm using the wrong keywords!
Module.parent called in your module lets you access to the exports of the file it was called from.
You can put the function below in your main.js and you can call module.parent.filename() in your module.
module.exports.filename = function () {
return __filename;
}

Requiring the same local node module from two directories results in two copies

I have a module (server.js) in the root of my project structure. It includes a module in a directory called lib:
var mongo = require('./lib/MongoUtils');
Another module in the lib directory also needs the 'MongoUtils' module, so it does:
var mongo = require('./MongoUtils');
The problem is I end up with two copies of the object (which is bad as it has some system resources like DB connections, etc.).
I've read the Node.js caching caveats documentation (http://nodejs.org/api/modules.html#modules_module_caching_caveats) and so it seems the problem is that I'm referring to the same module with two different paths and thus Node.js gives me two copies. Is this understanding correct?
How can I work around this? I didn't want to just dump my modules in node_modules since that's managed by npm via my package.json (and .gitignore-d). I thought about putting my local modules in the package.json (assuming that's possible), but then I'd need to be running 'npm install' whenever I make a change.
If this can't be done cleanly, I'll simply load the module in one place and pass it around, but that doesn't sound scalable if this occurs with lots of my modules.
I solved it. It turns out I typoed the capitalization of one of my modules. Node.js happily loaded the module and it worked fine, the only side effect was that I got the module loaded twice.
Here's an example. Note the capital B in the require statement in lib1.js.
main.js:
var lib1 = require('./lib/lib1')
, lib2 = require('./lib/lib2');
lib/lib1.js:
var lib2 = require('./liB2');
lib/lib2.js:
function MyClass() {
console.log('Constructor called');
}
module.exports = new MyClass();
If you run "node main.js" you'll get the following output:
Constructor called
Constructor called
If you fix the capital B in lib1.js and run it again, you'll see:
Constructor called

Resources