JavaScript problem with import, weird error - javascript

I have some code using library:
import { generateKeyPair } from 'jose/util/generate_key_pair'
async function funkcja () {
const {publicKey, privateKey} = await generateKeyPair('PS256')
console.log(publicKey)
console.log(privateKey)
}
funkcja()
and while trying to node it i get following error:
ubuntu#ubuntu-VirtualBox:~/Desktop/js$ node hello.js
/home/ubuntu/Desktop/js/hello.js:1
import { generateKeyPair } from 'jose/util/generate_key_pair'
^
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
I have no idea why this is happening, my friend is using exact same library and same code and on his computer it's working fine. (path to the library is correct) The only differennce is that he has node v12 and i have node v10.

Try this one
const { generateKeyPair } = require('jose/util/generate_key_pair');
Don't forget to use module.exports in generate_key_pair js file

How i read it in Update on ES6 Modules in Node.js the import of variables via curly brackets seems to be not supported in node.js.
it will simply not be possible to use the syntax:
import {foo, bar} from 'foobar';
But this would be possible:
import foobar from 'foobar';
console.log(foobar.foo(), foobar.bar());
So if generateKeyPair is a variable or function from 'jose/util/generate_key_pair' it should be:
import generate_key_pair from 'jose/util/generate_key_pair'
async function funkcja () {
const {publicKey, privateKey} = await generate_key_pair.generateKeyPair('PS256')
console.log(publicKey)
console.log(privateKey)
}
funkcja()

Related

why am i not able to import the class to another js file

class hello{
var1;
var2;
constructor(var1, var2){
this.var1 = var1;
this.var2 = var2;
}
getVar(){
console.log(this.var1);
console.log(this.var2);
}
}
class h1 extends hello{
var3 ;
constructor(var1, var2,var3)
{
super(var1,var2);
this.var3 = var3;
}
getAll(){
console.log(this.var1);
console.log(this.var2);
console.log(this.var3);
}
}
export {h1};
export {hello};
This is a module that I want to import from another file
This is the code of another file
import {h1,hello} from './temp'
let a = new h1("likith","ramu","asha");
a.getAll();
let b = new hello("raju","rahil");
b.getVar();
And this is the error that I'm getting for this code Please solve this problem
**
(node:14232) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use node --trace-warnings ... to show where the warning was created)
c:\Full stack dev Code\react.js\temp1.js:1
import {h1,hello} from './temp'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159: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:77:12)
at node:internal/main/run_main_module:17:47
[Done] exited with code=1 in 0.125 seconds
**
Since you are trying to import a module it will be better if you try exporting your classes as a module as well, like this, module.exports = { h1, hello };
and then you can import it in your other file like this, const { h1, hello } = require("./temp");.
Hope this solves your problem

Can not import custom created class in JS

I am importing the following class which I created like so
import Select from './operations/select.js'
select.js
export default class Select{
constructor(db){
this.db = db
}
allGenres(){
return new Promise((res,rej)=>{
this.db.all(`SELECT * FROM genre`,(err,rows)=>{
if(err) res(err)
else res(rows)
})
})
}
}
I wish to do something like
return await new Select(db).allGenres()
But I am getting the following
(node:38769) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/home/lucky/workspace/web/vibe-backend/index.js:2
import Select from './operations/select.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (node:internal/modules/cjs/loader:1018:16)
at Module._compile (node:internal/modules/cjs/loader:1066:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
thank you for yout time.
Change to:
const Select = require('./operations/select.js');

function rest parameters throw error

running:
$> node restparamstest.js
where:
restparamstest.js
var addTestNotification = function(x, ...theArgs) {
theArgs.forEach(function (post) {
console.log(post);
});
};
addTestNotification(1, 2, 4);
throws:
(function (exports, require, module, __filename, __dirname) { var addTestNotification = function(x, ...theArgs) {
^^^
SyntaxError: Unexpected token ...
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
on node version:
console.log(process.versions);
{ http_parser: '2.5.2',
node: '4.4.7',
v8: '4.5.103.36',
any ideas? Thanks!
Rest parameters are fully supported only since node 6.31. If you want to use them with earlier versions of node, you should use the --harmony flag.
You can see ES2015 support by node version here.
Give it a try like this
node --harmony restparamstest.js

JavaScript Exporting a class definition [duplicate]

This question already has answers here:
Destructuring in Node.JS
(3 answers)
Closed 7 years ago.
Can I export class definition in JavaScript? For example,
in file "HelloWorld.js":
'use strict';
class HelloWorld {
constructor(msg = 'Hello World~') {
this.message = msg;
}
sayHi() {
console.log(this.message);
}
}
module.exports = HelloWorld;
Then in "index.js"
'use strict';
var HelloWorld = require('HelloWorld');
var myObj = new HelloWorld;
myObj.sayHi();
if I do "node index.js", then I got the error below:
constructor(msg = 'Hello World~') {
^
SyntaxError: Unexpected token =
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (/data/users/soltiho/fbsource/fbcode/video_templates/test_env/index.js:3:18)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
my node is v5.5.0
Node doesn't support destructuring (yet), and using destructuring would be wrong anyways. There is nothing special about importing/exporting a class. Import it like any other module:
var myValue = require('myVModule');

Error: cannot find module when testing with mocha

I'm using babeljs to write an RPG engine library. I have two files:
dice.js
import assert from 'assert';
import Random from 'random-js';
export default class Dice {
constructor(maxNumber) {
assert(typeof(maxNumber) === "number", "maxNumber must be a number");
this._mt = Random.engines.mt19937();
this.minNumber = 1;
this.maxNumber = maxNumber;
}
makeThrow() {
this._mt.autoSeed();
return Random.integer(this.minNumber, this.maxNumber)(this._mt);
}
}
throwManager.js
import assert from 'assert';
import Dice from 'dice';
export default class ThrowManager {
constructor(settings) {
assert(settings.hasOwnProperty("numberOfDices"), "must set 'numberOfDices'");
assert(settings.hasOwnProperty("maxNumberInDice"), "must set 'maxNumberInDice'");
assert(settings.maxNumberInDice <= 1, "must have at least 1 dice");
this.settings = settings;
}
execute() {
var throwResults = [];
for (var d = 1; d <= this.settings.numberOfDices; d++) {
var dice = new Dice(this.settings.maxNumberInDice);
throwResults.push(dice.makeThrow());
};
return throwResults;
}
}
When I test them with mocha, I do these imports:
tests.js
var assert = require('assert');
var Amzhen = require('../Amzhen.js');
var random = require('random-js');
//tests here...
Yet when I run the tests, I get this:
Error: Cannot find module 'dice'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/joel/Amzhen.js/Amzhen.js:47:28)
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> (/home/joel/Amzhen.js/test/tests.js:2:14)
Any ideas why the dice module isn't being found?
I'm compiling the code with babel src --out-file Amzhen.js && mocha
You should use:
import Dice from './dice';
'dice' is not the name of a published, installed Node.js module, but a local file, so you should use ./dice with an appropriate path.
See also Module not found error in node.js

Categories