cannot import modules in react - javascript

I have made this utility which i want to import in another file :
const fetch = require('node-fetch');
/**
* #todo Add documentation
*/
class SimplicateApi {
constructor(key,secret){
this._key = key;
this._secret = secret;
this.baseUrl = 'https://simplicate.nl/api/v2';
this.options = {
headers: {
'Content-Type': 'application/json',
'Authentication-Key' : this._key,
'Authentication-Secret' : this._secret
}
}
}
get(endpoint) {
return fetch(`${this.baseUrl}${endpoint}`, this.options)
.then(res => res.json())
.then(json => json);
}
}
export default SimplicateApi;
In another file im importing it like this :
import SimplicateApi from '../../utils/SimplicateApi';
The error I receive :
(function (exports, require, module, __filename, __dirname) { import
{SimplicateApi} from '../../utils/SimplicateApi';
^
SyntaxError: Unexpected token {
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19) PS C:\Users\klmaa\OneDrive\Bureaublad\dexhub\client\src\components\cmInf
I removed everything even the fetch and just exported the class like this :
// import fetch from 'node-fetch';
/**
* #todo Add documentation
*/
class SimplicateApi {
}
export default SimplicateApi;
Now im importing it like this :
import SimplicateApi from '../../utils/SimplicateApi';
The error still looks like :
(function (exports, require, module, __filename, __dirname) { import SimplicateApi from '../../utils/SimplicateApi';
^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
PS C:\Users\klmaa\OneDrive\Bureaublad\dexhub\client\src\components\cmInf

Your code is mixing both CommonJs module and ES6 module.
In react, you should use ES6 module.
CommonJs module does not supported by React.You need to configure Babel for this.
const fetch = require('node-fetch'); // this wronng import syntax in React.
Changes should be
// if you are in react.
import fetch from 'node-fetch'; // for react
//if you are in Node.
class SimplicateApi {
}
module.exports = SimplicateApi;

Related

Implementing Puppeteer in node.js

I have my template which I want to export in pdf. The engine I am using is of PUG. I have this file in which I make a GET call to export the pdf.
But when I start my server - node index.js
I get error (shared below)
const express = require ('express');
var router = express.Router();
const puppeteer = require('puppeteer');
router.get('/export/html', (res,req) => {
res.render('template');
});
router. get('/export/pdf', (req, res) => {
(async () => {
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://localhost:3000/export/html');
// Get the "viewport" of the page, as reported by the page.
const dimensions = await page.evaluate(() => {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio
};
});
console.log('Dimensions:', dimensions);
await browser.close();
} catch(e) {
console.log(e);
}
})();
});
module.exports = router;
$ node index.js
E:\16pf\node_modules\puppeteer\lib\cjs\puppeteer\common\Page.js:707
catch {
^
SyntaxError: Unexpected token {
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (E:\16pf\node_modules\puppeteer\lib\cjs\puppeteer\common\Target.js:19:19)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
Shahrukh#DESKTOP-CQ0JNTJ MINGW64 /e/16pf
$
I am not sure why is this error occurring. Any help is appreciated.
You may use an old Node.js version than does not support optional catch binding. See support list: https://node.green/#ES2019-misc-optional-catch-binding
Nothing more than a javascript syntax error. Edit the line 707 with Nano:
nano +707 "E:\16pf\node_modules\puppeteer\lib\cjs\puppeteer\common\Page.js"
Change:
catch {
To:
catch(err) {
vsemozhebuty's answer may be better because even after you fix said javascript errors, you may have to fix a bunch more in order to get it to work.

Why export const helloWorld gives an error in firebase deploy and exports.helloWorld does not?

In a React Native project using Expo, I was trying to deploy the following cloud function using export:
Note: I use Javascript in the index.js.
export const helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
But I got this error:
Error: Error occurred while parsing your function triggers.
/Users.../functions/index.js:5
export const helloWorld = functions.https.onRequest((request, response) => {
^^^^^^
SyntaxError: Unexpected token export
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
Then I used exports.helloWorld... and it worked fine!
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
Can anyone explain why this happened?
Thanks
change it to:
const helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
module.exports = helloWorld
direct exports make the export one of exports. ie: refer by exports.something
Module.exports assign export directly where refered.

Unexpected identifier in async awaitCurrentBlock () while running my .js file

I am facing an issue while running my compile.js file using node compile.js .
My code:
const async = require('asyncawait/async');
const await = require('asyncawait/await');
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const { interface, bytecode } = require('./compile');
const provider = new HDWalletProvider(
'nut plug quality level uncle jeans retire guide eagle gossip cluster sudden',
'https://rinkeby.infura.io/v3/37097b2064214600912ad8a746ff433a'
);
const web3 = new Webs(provider);
const deploy = async (() => {
const accounts = await (web3.eth.Accounts());
console.log('Attempting to deploy from account', accounts[0]);
const result = await(new web3.eth.Contract(JSON.parse(interface))
.deploy({ data: bytecode, arguments: ['Hi there!'] })
.send({gas: '1000000', from: accounts[0]})
);
console.log('contract deployed to', result.options.address);
});
deploy();
After running : node compile.js
Error log:
/home/edureka/sankalp_practice/inbox/node_modules/eth-block-tracker/src/index.js:38
async awaitCurrentBlock () {
^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected token function
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/edureka/sankalp_practice/inbox/node_modules/web3-provider-engine/index.js:4:25)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
I did my analysis and it seems that "const HDWalletProvider = require('truffle-hdwallet-provider');" is calling for function async awaitCurrentBlock () in /home/edureka/sankalp_practice/inbox/node_modules/eth-block-tracker/src/index.js.
So please let me know how to resolve it.
system: Ubuntu
version of node: v6.11.4
version of npm : 5.4.2
your dependency uses "async awaitCurrentBlock" that looks like node 8.* in which case you're simply using too old version of node. You want that dependency, then you have to update, but that will break your code in another way -> you're importing dependencies "async" and "await" which are reserved keywords in Node 8, so you'll have to update your syntax too

Call a helper functions anywhere in the applicaion - Node/Express

I have a controller
import request from 'request-promise'
import env from 'dotenv'
const dotenv = env.config();
/*==================================
= getCPEInfo =
==================================*/
function getCPEInfo(req, res)
{
var $cpeMac = req.body.cpeMac;
return new Promise((resolve, reject) => {
request({ uri: `${process.env.API_HOST}/vse/ext/vcpe/${$cpeMac}` })
.then((cpe) => resolve(JSON.parse(cpe).data))
.catch((error) => reject(error));
});
}
module.exports = {
getCPEInfo
};
I want to call this getCPEInfo() on my other files in my project
I tried import
import generalController from './controllers/general.js'
and call it
generalController.getCPEInfo();
I kept getting
[nodemon] restarting due to changes...
[nodemon] starting `babel-node ./index.js`
/Users/bheng/Desktop/express-app/index.js:72
router.post('/getCPEInfo/:cpeMac', generalController.getCPEInfo);
^
ReferenceError: generalController is not defined
at Object.<anonymous> (/Users/bheng/Desktop/express-app/index.js:37:36)
at Module._compile (module.js:643:30)
at loader (/Users/bheng/Desktop/express-app/node_modules/babel-register/lib/node.js:144:5)
at Object.require.extensions.(anonymous function) [as .js] (/Users/bheng/Desktop/express-app/node_modules/babel-register/lib/node.js:154:7)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at Object.<anonymous> (/Users/bheng/Desktop/express-app/node_modules/babel-cli/lib/_babel-node.js:154:22)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
[nodemon] app crashed - waiting for file changes before starting...
Can someone please give me a hint ?
import generalController from './controllers/general.js' will refer to the default export from the module, you need to refactor your controller :
import request from 'request-promise'
import env from 'dotenv'
const dotenv = env.config();
/*==================================
= getCPEInfo =
==================================*/
function getCPEInfo(req, res)
{
var $cpeMac = req.body.cpeMac;
return new Promise((resolve, reject) => {
request({ uri: `${process.env.API_HOST}/vse/ext/vcpe/${$cpeMac}` })
.then((cpe) => resolve(JSON.parse(cpe).data))
.catch((error) => reject(error));
});
}
var Mycontroller = {
getCPEInfo
};
export default MyController
Take a look here.

Meteor.js: How to use a phantom.js?

I need to use a phantom with the meteor. If I use a separate script, everything works. If I'm using in with the meteor, I get an error.
import React, { Component } from 'react';
var phantom = require('phantom');
phantom.create().then(function(ph) {
ph.createPage().then(function(page) {
page.open('https://stackoverflow.com/').then(function(status) {
console.log(status);
page.property('content').then(function(content) {
console.log(content);
page.close();
ph.exit();
});
});
});
});
export default class App extends Component {
render() {
return (
<div className="container"></div>
);
}
}
C:\OpenServer\domains\EM-topface-like\node_modules\phantom\lib\phantom.js:53 function createLogger({ logLevel = defaultLogLevel } = {}) { 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 Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\OpenServer\domains\EM-topface-like\node_modules\phantom\lib\index.js:7:16)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10) Exited with code: 1 Your application is crashing. Waiting for file change.
How to fix?

Categories