Static variable in nodejs - javascript

I am using ES6 style code within NodeJS.
When trying to create a static variable I get an error.
Code:
'use strict';
module.exports = class Count {
static addToCounter() {
//this.count = this.count + 1 || 1;
this.count = this.count + 1;
console.log(`count: `+this.count);
}
static count = "";
}
Error:
static count = "";
^
SyntaxError: Unexpected token =
at new Script (vm.js:74:7)
at createScript (vm.js:246:10)
at Object.runInThisContext (vm.js:298:10)
at Module._compile (internal/modules/cjs/loader.js:646:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)
at Module.require (internal/modules/cjs/loader.js:626:17)
at require (internal/modules/cjs/helpers.js:20:18)
What is my mistake?

This proposal is still in stage-2. As of now, without the babel plugin transform-class-properties, it is not possible to use the assignment operator along with the static keyword.

If you are not transpiling, you will need to be using at least Node.js v12.4.0 for static class fields. https://node.green/#ESNEXT-candidate--stage-3--static-class-fields-public-static-class-fields shows supported features across Node.js versions.
Also, inside your addToCounter function, you would also need to use Count.count = Count.count + 1. If you want to be able to store properties on each instance, then you would need to remove the static keywords before both the method and the property declaration.

Related

Is there a way to get a variable or function from one file to another file in javascript?

I have a file for my Blockchain called gale.js, and I need the Blockchain variable to get into my miner.js file:
let galeCoin = new Blockchain(); // My Blockchain
Can I access this variable from my miner.js file so I can run the minePendingTransactions() function from the Blockchain class
var galeCoin = /* the coin imported from the gale.js file */
var minerAdress = "0xOTUYboIUYEO5C274OUIYGo8isYOCYW6o87TO"; // SHA256 Hash for the miner
while (true) {
minePendingTransactions(minerAdress); // mine (forever)
}
I would also like to access this variable in my user.js file:
var galeCoin = /* the coin imported from the gale.js file */
var userAdress = galeCoin.newAdress(); // A new adress for the user
// I will add the code here later...
And many other files!
But I can't seen to access the variable from the other files!
I tried this:
let galeCoin = new Blockchain();
export { galeCoin };
import { galeCoin } from './gale.js'
but that gives me this error when I run miner.js using node miner.js:
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module 'gale.js'
Require stack:
- /Users/Movies/Desktop/devProjects/Blockchain/SecondTry/miner.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/Movies/Desktop/devProjects/Blockchain/SecondTry/miner.js:1:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/Users/Movies/Desktop/devProjects/Blockchain/SecondTry/miner.js' ]
}
I dont understand the error message
I need help as soon as posible!
NOTE: My files are in /Users/Movies/Desktop/devProjects/Blockchain/SecondTry/
Try using the following to import galeCoin from gale.js:
var {galeCoin} = require('./gale.js');
You'll also need to export the galeCoin object from gale.js. You can use the following (append somewhere at the end of gale.js):
module.exports = {galeCoin};
Then you're going to want to run npm install gale.js to ensure that module is added to the node_modules directory. For this you're going to want to make sure the node_modules is in the same director as miner.js. If it is not, npm -g install gale.js.
I should note, I'm assuming you're using node.js, which from the error you threw, seems to be the case.
I hope this was helpful:)
Try :
export let galeCoin = new Blockchain();
//add export statement at the beginning of the line where you declare your variable
You can read about it here: https://javascript.info/import-export

How to "require" a JS class that contains JSX?

I'm trying to call functions of my JS class which extends react.
I have one file RunTest.js which looks like this:
let Builder = require('./Builder');
let b = Builder();
b.say("Hello World!");
My Builder.js in the same directory looks something like this:
class Builder extends React.Component{
...
}
module.exports = { Builder }
And when I run with node RunTest.js I receive the following error:
bash-3.2$ node RunTest.js
/Users/jonahlibrach/Documents/project/prototypes/bron/v1/java/prototype/
server/static/protocol/Builder.js:322
<div class="navbar">
^
SyntaxError: Unexpected token <
at Module._compile (internal/modules/cjs/loader.js:743:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:810
:10)
at Module.load (internal/modules/cjs/loader.js:666:32)
at tryModuleLoad (internal/modules/cjs/loader.js:606:12)
at Function.Module._load (internal/modules/cjs/loader.js:598:3)
at Module.require (internal/modules/cjs/loader.js:705:19)
at require (internal/modules/cjs/helpers.js:14:16)
at Object.<anonymous> (/Users/jonahlibrach/Documents/project/prototy
pes/bron/v1/java/prototype/server/static/protocol/RunTest.js:1:15)
at Module._compile (internal/modules/cjs/loader.js:799:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:810
:10)
How do I use this class in node?
You cannot use modules that contain JSX in Node.js without first transpiling them to JavaScript (e.g. with Babel).

Module not found unless I use a complete path when creating plugins in Hapi

I'm trying to familiarise myself with HapiJS and have been playing around with it this week, I've run into a problem with plugins and paths. I get an error regarding the path I specify when I require a file. I can't use " ./ " without getting an error. The only way to overcome the error is to use the full complete path.
Here's my code that works:
'use strict';
const indexController = require('/Users/mylaptop/docker-node/controllers/IndexController.js');
module.exports.plugin = {
name: 'myPlugin',
version: '1.0.0',
register: async function (server, options) {
// Create a route for example
server.route({
method:'GET',
path:'/test',
handler: function (request, h) {
return indexController.loadIndex(h);
}
});
}
};
However, if I try to require my IndexController file this way:
const indexController = require('./controllers/IndexController.js');
Then I get this error:
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module '/Users/mylaptop/docker-node/Users/mylaptop/docker-node/controllers/IndexController.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (/Users/mylaptop/docker-node/config/routes/index.js:5:25)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
It doesn't work inside of my plugin, yet outside of my plugin, requiring files this way works fine.
What could be the problem? How can I solve it?
Thanks in advance.
Problem solved with:
const indexController = require('../../controllers/IndexController.js');
My project root folder was 2 directories away, hence ../../ working for me.

Node.js "Cannot read property 'prototype' of undefined" error - Node.js, MongoDB and Angularjs book

I am working through Brad Dayley's Node.js, MongoDB and Angularjs book and I'm stuck on one of his exercises (Listing 4.4). I have a simple script emitterListener.js that is as follows the script is designed to makes checks on an account.
var events = require('events');
function Account() {
this.balance = 0;
events.EventEmitter.call(this);
this.deposit = function(amount) {
this.balance += amount;
this.emit('balanceChanged');
};
this.withdraw = function(amount) {
this.balance -= amount;
this.emit('balanceChanged');
};
}
Account.prototype._proto_ = events.EventEmitter.prototype;
function displayBalance() {
console.log("Account balance: $%d", this.balance);
}
function checkOverdraw() {
if (this.balance < 0) {
console.log("Account Overdrawn!!!!!");
}
}
function checkGoal(acc, goal) {
if (acc.balance > goal) {
console.log("Goal Achieved!!!!!");
}
}
var account = new Account();
account.on("balanceChanged", displayBalance);
account.on("balanceChanged", checkOverdraw);
account.on("balanceChanged", function() {
checkGoal(this, 1000);
});
account.deposit(220);
account.deposit(320);
account.deposit(600);
account.withdraw(1200);
When I run this I get the error.
TypeError: Object #<Account> has no method 'on'
at Object.<anonymous> (/Users/506132/web/emitterListener.js:35:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
From my limited understanding after researching I think this means that the "on" module is not being loaded. I found a solution that suggested something similar to adding this to line 1
var events = require('events').on;
which then results in the error.
TypeError: Cannot read property 'EventEmitter' of undefined
at Object.<anonymous> (/Users/506132/web/emitterListener.js:16:35)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
Following the logic from the first fix I tried implementing the same fix but with EventEmitter
var events = require('events').EventEmitter;
Hooray it looks like it worked.... or not......and now I get this error
TypeError: Cannot read property 'prototype' of undefined
at Object.<anonymous> (/Users/506132/web/emitterListener.js:17:48)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
I tried adding the below code thinking why not?
var events = require('events').prototype;
and it just brings me back to the same error from before
TypeError: Cannot read property 'EventEmitter' of undefined
at Object.<anonymous> (/Users/506132/web/emitterListener.js:16:35)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
What am I doing wrong here? How should I go about debugging this and where should I look? Thanks in advance for helping a newbie out.
Cheers.
process.EventEmitter is deprecated, use require('events') instead.
Search through all your reference files (should be in multiple files) for:
var EventEmitter = process.EventEmitter
An where ever it exists, change that line to this:
var EventEmitter = require('events')
I'll post it as an answer so this question won't get marked as unanswered.
You should change:
Account.prototype.__proto__ = events.EventEmitter.prototype;
to:
Account.prototype = Object.create(events.EventEmitter.prototype);
var EventEmitter = process.EventEmitter
is deprecated in high version of node, use var EventEmitter = require('events') instead
This compilation error because of versions conflicts of npm and node. I had the same issue in my project. I resolved after install the same compatible versions of npm and node as on another machine.
Check:
nmp -v
and
node -v.
All the confusion with the actual example is the first line of code.
var events = require('events');
After Node v6.1.0 this line of code will store EventEmmiter object inside events variable, so there is no need to access it explicitly later.
Solution is very simple, just change
events.EventEmitter.call(this);
to:
events.call(this)
And change
Account.prototype._proto_ = events.EventEmitter.prototype;
to:
Account.prototype._proto_ = events.prototype;
I had the same problem a few minutes ago, I decided to downgrade node to version 6.x, then it worked

Node JS is says method isn't there when it clearly is

Alright, so I've created a test project to show off this error. The error being that Node JS can't find my getStr function in my Another object.
This is the code:
test.js
var Another = require('./another.js');
var Other = require('./other.js');
var otherStr = Other.getStr();
console.log(otherStr);
other.js
var Another = require('./another.js');
var str = Another.getStr();
another.js
var Other = require('./other.js');
var str = "other String";
exports.getStr = function(){
return str;
}
And this is my output:
C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test>node test.js
C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\other.js:3
var str = Another.getStr();
^
TypeError: Object #<Object> has no method 'getStr'
at Object.<anonymous> (C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\ot
her.js:3:19)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\an
other.js:1:75)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test>
So how do I get Node JS to see Another's getStr function in Other?
What you're dealing with here is a circular dependency. Node.js will let you load modules in a circular way but you need to design your code to account for it. Generally speaking, a circular dependency is a sign that the design is suffering from some flaw. In the code you've shown in the question, another requires other but does nothing with it. So the simplest fix would be to change another so that it does not require other.
If you have to keep the circular dependency for some reason or you want to experiment with circular dependencies for learning purposes, then this would be another possible fix:
var str = "other String";
exports.getStr = function(){
return str;
}
var Other = require('./other');
// Actually do something with Other down here.
By the time other is required another will at least have getStr available. So this takes care of the immediate issue. Note however that your other module does not export anything so your test.js file will still fail at var otherStr = Other.getStr(); Probably you forgot to add this:
exports.getStr = function(){
return str;
}
(Note: I've modified the require call so that it requires other without the .js suffix. Generally, you don't want to put suffixes in your require calls. You want to put a module name which Node can resolve to a file, a package, or something else.)

Categories