Error while running typescript node using geo-tz in build file - node.js

I am using geo-tz in our Typescript Nodejs application for getting the geolocation details. When i am running the node server locally, it's working fine but when taken a node server build , i am getting an error like the below while calling geo-tz function like this:
import * as geoTz from 'geo-tz';
const testGeotz= ()=>{
try{
const coords = [-122.350070,47.650499]
let name = geoTz(coords[1], coords[0])[0];
}catch (e) {
console.log(e);
}
}
Why is it happening like this ?
My node version - 12.16.3
geo-tz version - 6.0.0
I even tried downgrading the geo-tz version and tried to upgrade to latest v6.0.1 .Still same response.
Please tell me whether I have missed out any dependency .

Related

NPM and NodeJS Compatibility: NodeJS works from PM prompt, but not script

I am attempting to get a lighthouse script running in Node.JS (which I am new to). I followed the intial instructions here https://github.com/GoogleChrome/lighthouse/blob/master/docs/readme.md#using-programmatically. I was able to complete the prior steps in the package manager console (Visual Studio 2017):
npm install -g lighthouse
lighthouse https://airhorner.com/
//and
lighthouse https://airhorner.com/ --output=json --output-path=./report/test1.json
However, I do get an initial warning that NPM only supports Node.JS in versions 4 through 8 and recommends a newer version. The problem is I am running Node v12 and NPM v5 - both the latest.
When I create a script version like below (app.js)
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const config = {
extends: 'lighthouse:default',
settings: {
emulatedFormFactor: 'desktop',
onlyCategories: 'performance',
output: 'json',
outputPath: './report.json'
}
};
function launchChromeAndRunLighthouse(url, opts = null, config) {
return chromeLauncher.launch().then(chrome => {
opts.port = chrome.port;
return lighthouse(url, opts, config).then(results => {
return chrome.kill().then(() => results.lhr);
});
});
}
// Usage:
launchChromeAndRunLighthouse('https://airhorner.com/', config).then(results => {
// Use results!
});
And run the command
C:\src\project> node app.js
I get the error - Cannot find module 'lighthouse'
don't install lighthouse locally use it inside your working dir .
first start by running npm init that will create the package.json file inside the current working dir
then npm install --save lighthouse will download it and save it to node_modules now you can use it locally inside your working dir
it should look something like this
app.js
package.json
node_modules/
then run node app.js

Getting Error when try to deploy contract from node js using truffle-contract

I am getting error, I am following this documentation:
https://www.npmjs.com/package/truffle-contract
Whenever I call deploy function then I received this error.
import Web3 from 'web3';
import propertyContractJson from './contracts/PropertyContract.json';
var provider = new Web3.providers.HttpProvider("http://localhost:8545");
var contract = require("truffle-contract");
var MyContract = contract({
abi: propertyContractJson,
address: '0x0A08a58433108f1a8dF080Ef552f137b2f7b8ce0' // optional
// many more
})
MyContract.setProvider(provider);
var deployed;
MyContract.deployed().then(function(instance) {
deployed = instance;
return instance;
}).then(function(result) {
// Do something with the result or continue with more transactions.
});
Following is the error I get when deployed() method is called
Error: Unhandled rejectionNode error: {"message":"Method [object
Object] not supported.","code":-32000,"data":{"stack":"Error: Method
[object Object] not supported.\n at GethApiDouble.handleRequest
(C:\Program
Files\WindowsApps\Ganache_2.0.0.0_x64__zh355ej5cj694\app\resources\app.asar\node_modules\ganache-core\lib\subproviders\geth_api_double.js:67:16)\n at next (C:\Program
Files\WindowsApps\Ganache_2.0.0.0_x64__zh355ej5cj694\app\resources\app.asar\node_modules\ganache-core\node_modules\web3-provider-engine\index.js:116:18)\n
at GethDefaults.handleRequest (C:\Program
Files\WindowsApps\Ganache_2.0.0.0_x64__zh355ej5cj694\app\resources\app.asar\node_modules\ganache-core\lib\subproviders\gethdefaults.js:15:12)\n
at next (C:\Program
Files\WindowsApps\Ganache_2.0.0.0_x64__zh355ej5cj694\app\resources\app.asar\node_modules\ganache-core\
The problem comes from the version of web3, it is currently not supported by truffle.
When you install Web3, the installed version is 1.0.0 (a beta version) while truffle works with the 0.20 (the stable version)
To solve this problem, delete the node_modules folder and edit the version of web3 in the package.json folder, then run the command npm install and rebuild the contracts with > build command in truffle. The API should work. If you still want to use version 1.0.0, I invite you to read this article, I have not tested it yet.

"ReferenceError: WebSocket is not defined" when using RxJs WebSocketSubject and Angular Universal

I'm setting up an angular 6.x univeral project in order to leverage its SSR (Server-Side Rendering) capabilities. In my app, I'm using websocket communication using RxJs.
More specifically, I'm, using WebSocketSubject and webSocket in my angular universal 6.x project, which works fine on the browser platform. However, when running the node web server (that contains the SSR stuff (Server-Side Rendering)), an error is thrown:
ReferenceError: WebSocket is not defined
Example code:
// not actually code from the reproduction repo
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
const socket: WebSocketSubject<any> = webSocket('wss://echo.websocket.org');
socket.subscribe(msg => doSomething(msg));
Please note, that the error doesn't occur on the browser version of the app (i.e. ng serve won't throw the error), but only after compiling the SSR stuff and running the express web server. To reproduce the error, the builds have to be run first:
# install dependencies
npm install
# build angular bundles for browser and server platforms
npm run build:client-and-server-bundles
# build the webserver
npm run webpack:server
# start the webserver
npm run serve:ssr
# the app is now being served at http://localhost:8081/
# open it in the browser and the error will occur: 'ReferenceError: WebSocket is not defined'
I've also set up a reproduction repo.
Environment I'm using:
Runtime: Angular 6
RxJS version: 6.2.0, 6.2.1, 6.2.2 (tested all)
Edit 2018-08-02
I was able to address the problem more accurately. It seems, that this is also a webpack problem. Angular Universal creates a js bundle for running the angular app on the node server, but there is natively no websocket implementation on Node. Therefore, it has to be added manually as a dependency (npm package). I tried adding it to the js server bundle (const WebSocket = require('ws'); manually, which resolves the problem (i.e. ReferenceError disappears). However, when I add it to the TypeScript code that gets transcompiled into the js bundle later on, it won't work.
Further details
The webpack loader ts-loader is used for compiling TypeScript => JavaScript
The websocket depedency was added to the package.json: "ws": "^6.0.0"
Attempting to reference the ws dependency by adding const WebSocket = require('ws'); to the uncompiled TypeScript code won't resolve the issue. It would get compiled into var WebSocket = __webpack_require__(333); in the js output file, the dependency won't be able to be resolved.
Manually changing var WebSocket = __webpack_require__(333); => const WebSocket = require('ws'); in the compiled js file would resolve the issue, but of course it's a hack.
So, the questions are:
Can I "force" webpack to compile the dependency const WebSocket = require('ws'); => const WebSocket = require('ws'); (no changes)?
Or, would it might be a better solution, to register this dependency in the angular universal npm package and create a pull request?
The RxJS webSocket function can receive a WebSocket Constructor as an argument. This can be used to run webSocket in a non-browser/universal environment like this.
const WebSocketConstructor = WebSocket || require('ws')
const socket: WebSocketSubject<any> = webSocket({
url: 'wss://echo.websocket.org',
WebSocketCtor: WebSocketConstructor,
});
// OR...
import { WebSocket, ...otherStuff... } from 'ws';
import { webSocket, ...otherStuff... } from 'rxjs/webSocket';
const socket$ = webSocket({
url: 'wss://someplace.com',
WebSocketCtor: WebSocket,
});
All it takes is this:
// set WebSocket on global object
(global as any).WebSocket = require('ws');
And of course, we need the ws dependency as well in the package.json:
npm i ws -s
In nodeJS apps with ES6 or similar, you must use this:
global.WebSocket = require('ws')
For example:
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
global.WebSocket = require('ws'); // <-- FIX ALL ERRORS
const subject = webSocket('ws://...');
No more errors.
My first answer!! Cheers
I created a npm package using websockets.
To provide compatibility for server side js and browser js i use this code.
(Note: it is typescript)
if (typeof global !== 'undefined') {
(global as any).WebSocket = require('ws');
}
Like you mentioned, the browser already has a WebSocket in its global object window but node does not.
Since the browser does not have global, this simple check works well.
Compiled code:
if (typeof global !== 'undefined') {
global.WebSocket = require('ws');
}

Module did not self register with Talib and AVA

I'm getting a Module did not self register error I am unable to get rid of using talib and ava.
I have tried Node 8.9.0 as well as 9.0.0, upgraded AVA and tried stable and dev branches of talib. I am running test serially as well. And of course I have cleared and rebuilt my node_modules folder - this is evidently not a case of changing node versions like I have seen posted.
Test:
test.serial( t => {
const talib = require('talib')
})
test.serial( t => {
const talib = require('talib')
})
The first test works but more than one throws that error. In the past I have had success clearing modules with clear-module and import-fresh but not this time.
const clear = require('clear-module')
const fresh = require('import-fresh')
test.serial(t => {
clear.all('talib')
const talib = fresh('talib')
})
I don't know where that error comes from, but one thing to keep in mind is that AVA starts running your tests asynchronously, e.g. not when the file is first loaded. Do you need to require talib outside of test.serial()?

TypeError: require(...).connect is not a function

node version: v4.4.4
npm version: 3.9.2
ionic version (app): 2.0.0-beta.7
amqplib version: 0.4.1
I am currently trying to develop an app using Ionic 2 framework and I have decided to introduce messaging in my app by using RabbitMQ within this library. Feel free to inspect the code here for any further reference.
First of all, I installed the library manually using npm install https://github.com/squaremo/amqp.node.git because the release version from npm is outdated.
After that, I added the Typescript definitions for the library via typings install dt~amqplib --global --save.
I created a new page for my app called Page2 where the library is imported...
import * as amqp from 'amqplib/callback_api';
[...]
... and used to connect to the server...
[...]
setConnection() {
amqp.connect(this.connectionUrl, (err: any, connection: amqp.Connection) => {
this.connection = connection;
this.connection.createChannel((err: any, channel: amqp.Channel) => {
this.channel = channel;
this.channel.assertExchange(this.exchange, 'topic', { durable: false });
});
});
}
[...]
The problem comes when I try to run it (I have done it using both an emulator and a native device running Android). If I try to hit the Set connection button, I get the following error:
The error is linked to the line sock = require('net').connect(sockopts, onConnect); of connect.js file. Is there any trouble with NodeJS Net module in the library or is it a misconfiguration I made somewhere in my app?, thanks in advance.
There is no nodeJS server in an ionic app that your library can use.

Resources