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

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.

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.

cannot import modules in react

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;

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

Deploying nuxt edge to firebase with function get an error

I try to deploy nuxt project using the latest version of Nuxt which is nuxt-edge to firebase. This is my function code.
const { Nuxt } = require('nuxt-edge')
const express = require('express')
const functions = require('firebase-functions')
const app = express()
const config = {
dev: false,
buildDir: 'nuxt',
build: {
extractCSS: true,
cache: false,
parallel: true,
publicPath: '/assets/'
}
}
const nuxt = new Nuxt(config)
const handleRequest = (req, res) => {
return new Promise((resolve, reject) => {
nuxt.render(req, res, promise => {
promise.then(resolve).catch(reject)
})
})
}
app.use(handleRequest)
exports.jefrydcossr = functions.https.onRequest(app)
It successfully run locally with firebase serve --only hosting,function command. But when I deployed it online and I open the hosting url, I got server error 500.
After I looked at the error log, I got error like this
2018-06-14T12:43:26.094Z D jefrydcossr: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: Error: only one instance of babel-polyfill is allowed
at Object.<anonymous> (/user_code/node_modules/nuxt-edge/node_modules/babel-polyfill/lib/index.js:10:9)
at Module._compile (module.js:577:32)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/user_code/node_modules/nuxt-edge/dist/nuxt-legacy.js:50:1)
at Module._compile (module.js:577:32)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
2018-06-14T12:43:26.206Z E jefrydcossr: undefined
2018-06-14T12:51:04.440Z N jefrydcossr: undefined
2018-06-14T12:53:28.052Z N jefrydcossr: undefined
The repository of this project here https://github.com/jefrydco/jefrydco-id

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