TypeError: require(...).connect is not a function - node.js

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.

Related

Vue Error - Can't resolve 'https' when importing package

I'm trying to make a Vue project and use an npm package for connecting to the retroachievements.org api to fetch some data, but I'm getting an error. Here's my process from start to finish to create the project and implement the package.
Navigate to my projects folder and use the vue cli to create the project: vue create test. For options, I usually chose not to include the linter, vue version 2, and put everything in package.json.
cd into the /test folder: cd test and install the retroachievements npm package: npm install --save raapijs
Modify App.vue to the following (apologies for code formatting, not sure why the post isn't formatting/coloring it all properly...):
const RaApi = require('raapijs');
export default {
name: 'App',
data: () => ({
api:null,
user: '<USER_NAME>',
apiKey: '<API_KEY>',
}),
created() {
this.api = new RaApi(this.user, this.apiKey);
},
}
run `npm run serve' and get the error:
ERROR in ./node_modules/raapijs/index.js 2:14-30
Module not found: Error: Can't resolve 'https' in 'C:\Projects\Web\test\node_modules\raapijs'
I'm on Windows 10, Node 16.17.0, npm 8.15.0, vue 2.6.14, vue CLI 5.0.8, raapijs 0.1.2.
The first solution below says he can run it without error but it looks like the exact same code as I'm trying. Can anyone see a difference and a reason for this error?
EDIT: I reworded this post to be more clear about my process and provide more info, like the versions.
This solution works for me. I installed raapijs with npm install --save raapijs command. Then in my Vue version 2 component I used your code as follow:
const RaApi = require('raapijs');
export default {
data: () => ({
api: null,
user: '<USER_NAME>',
apiKey: '<API_KEY>',
}),
created() {
this.api = new RaApi(this.user, this.apiKey);
},
};
It seems the raapijs package was designed to be used in a Node environment, rather than in Vue's browser based environment, so that's the reason I was getting an error. The package itself was looking for the built in https package in Node, but since it wasn't running in Node, it wasn't finding it.
So I solved my problem by looking at the package's github repo and extractingt he actual php API endpoints that were being used and using those in my app directly, rather than using the package wrapper. Not quite as clean and tidy as I was hoping but still a decent solution.

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

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 .

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

"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');
}

typescript error in redis - on event

import * as redis from 'redis'
import config from '../../config/config'
const client = redis.createClient(config.redis.port, host, config.redis.options);
client.on('ready', () => {
console.log('redis is ready.')
});
getting below error in typescript
[ts] Property 'on' does not exist on type '{ address: any; connection_options: { [x: string]: any; }; connection_id: number; connected: bool...'. any
First of all, have you installed the type module for the redis module? I highly recommend doing that as it helps TypeScript compiler and potentially your IDE to know what commands and interfaces are available in the redis module. To do so:
npm i --save-dev #types/redis
Second, try adding the .on('error', console.error) to see if your client is emitting any meaningful connection errors. There could be a problem with you client credentials, which fails the connections.
Lastly, you can completely skip the .on('ready', ...) event handler as it's not necessary. The redis module queues all the commands sent before the connection is established, and will automatically send them once it's successfully connected. You can just start testing the client with simple set and get commands.
I encountered the same problem. Everything seemed fine, redis typings were installed (actually already provided by the redis package).
However, I simply forgot to install the nodejs types... Without these typing, typescript isn't aware of, i.a, the EventEmitter.
Try installing:
npm install --save-dev #types/node

Resources