Paho MQTT: Possible importing error? - javascript

I recently downloaded paho-mqttvia yarn. The problem is I am not sure if I am importing it correctly, because I am getting an error:
Cannot read property 'Client' of undefined
The way I am importing and using it is like this:
import Paho from 'paho-mqtt';
var client = new Paho.MQTT.Client(location.host, location.port, location.clientID)
const MQTTConnectAndMessage = (message) => {
client.connect({onSuccess: sendMQTTMessage})
}
const sendMQTTMessage = (msg) => {
let message = new Paho.MQTT.Message(msg);
message.destinationName = location.messageDestination;
client.send(message);
}
location.host = a string for the IP
location.port = a number for the port
location.clientID = a string for the clientID
If it is relevant, I am attempting to use it within a React Native app.
Maybe this module is not meant to be downloaded via NPM or Yarn? Or maybe I am not supposed to be importing "Paho"?
EDIT: when using react-native-paho-mqtt--this is the code I am using:
const client = new Client({ uri: 'ws://myiphere/ws', port: 1883, clientId: 'clientId', storage: myStorage});
const sendMQTTMessage = (msg) => {
client.on('connectionLost', (responseObject) => {
if (responseObject.errorCode !== 0) {
console.log("connection lost!");
}
});
client.on('messageReceived', (message) => {
console.log(message.payloadString);
});
client.connect()
.then(() => {
const message = new Message(msg);
message.destinationName = 'F2/BOX2/LED3';
client.send(message);
})
.catch((responseObject) => {
if (responseObject.errorCode !== 0) {
console.log('onConnectionLost:' + responseObject.errorMessage);
}
});
}
export {
sendMQTTMessage
}
I notice that whenever I enter anything that isn't prefaced with ws:// (web sockets) I would get a URI error.

The paho-mqtt library has changed, and the example code is incorrect
var client = new Paho.MQTT.Client(location.host, location.port, location.clientID)
Should be changed to (remove MQTT from Object path):
var client = new Paho.Client(location.host, location.port, location.clientID)
See the "breaking changes" in the GitHub README page:
paho.mqtt.javascript

Try this react-native compatible library: https://www.npmjs.com/package/react-native-paho-mqtt
yarn add react-native-paho-mqtt

Related

Node grpc client error: TypeError: _d.substring is not a function

I have encountered strange issue and I am unable to make a call to my grpc server from node.
I am using:
"#grpc/grpc-js": "^1.6.8",
"#grpc/proto-loader": "^0.7.0",
Node version: 16.14.2
npm version: 8.5.0
And im my client file:
const grpc = require('#grpc/grpc-js');
const PROTO_PATH_LOGS_REQUEST = __dirname + '/proto/Attempt.proto';
const protoLoader = require('#grpc/proto-loader');
const AuthService = require('./AuthService');
const packageDefinition = protoLoader.loadSync(
PROTO_PATH_LOGS_REQUEST, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
const ServiceDefinition = grpc.loadPackageDefinition(packageDefinition).com.example.AttemptService;
const updateAttempt = async (id, operationStatus) => {
const client = new ServiceDefinition('127.0.0.1:6513', grpc.credentials.createInsecure());
console.log(`Created gRPC client`);
const request = {
id: id,
status: operationStatus
};
const meta = new grpc.Metadata();
const token = AuthService.generateServiceToken();
meta.add('Authorization', `Bearer ${token}`);
await client.UpdateAttempt(request, meta);
}
My proto file:
syntax = "proto3";
package com.example;
message AttemptUpdateRequest {
string id = 1;
string status = 2;
}
message ContactAttempt {
string status = 1;
}
service AttemptService {
rpc UpdateAttempt (AttemptUpdateRequest) returns (ContactAttempt);
}
So my app crashes before reaching "Created gRPC client" log.
After putting new ServiceDefinition('127.0.0.1:6513', grpc.credentials.createInsecure()); inside try catch I received:
TypeError: _d.substring is not a function
And this error comes from node_modules\#grpc\grpc-js\build\src\channel.js:202:201 from this lines:
const error = new Error();
logging_1.trace(constants_1.LogVerbosity.DEBUG, 'channel_stacktrace', '(' + this.channelzRef.id + ') ' + 'Channel constructed \n' + ((_d = error.stack) === null || _d === void 0 ? void 0 : _d.substring(error.stack.indexOf('\n') + 1)));
The best part is that commenting this two lines solves this issue... But I need to put my app inside a Docker container so this is not an acceptable solution.
Did anybody encounter similar issue?

Sveltekit & Fleek (IPFS) import syntax problem?

I have managed to use fleek to update IPFS via straight javascript. I am now trying to add this functionality to a clean install of a svelteKit app. I think I am having trouble with the syntax around imports, but am not sure what I am doing wrong. When I click the button on the index.svelte I get the following error
Uncaught ReferenceError: require is not defined
uploadIPFS upload.js:3
listen index.mjs:412..........(I truncated the error here)
A few thoughts
I am wondering if it could be working in javascript because it is being called in node (running on the server) but running on the client in svelte?
More Details
The index.svelte file looks like this
<script>
import {uploadIPFS} from '../IPFS/upload'
</script>
<button on:click={uploadIPFS}>
upload to ipfs
</button>
the upload.js file looks like this
export const uploadIPFS = () => {
const fleek = require('#fleekhq/fleek-storage-js');
const apiKey = 'cZsQh9XV5+6Nd1+Bou4OuA==';
const apiSecret = '';
const data = 'pauls test load';
const testFunctionUpload = async (data) => {
const date = new Date();
const timestamp = date.getTime();
const input = {
apiKey,
apiSecret,
key: `file-${timestamp}`,
data
};
try {
const result = await fleek.upload(input);
console.log(result);
} catch (e) {
console.log('error', e);
}
};
testFunctionUpload(data);
};
I have also tried using the other import syntax and when I do I get the following error
500
global is not defined....
import with the other syntax is
import fleekStorage from '#fleekhq/fleek-storage-js';
function uploadIPFS() {
console.log('fleekStorage',fleekStorage)
};
export default uploadIPFS;
*I erased the api secret in the code above. In future I will store these in a .env file.
Even more details (if you need them)
The file below will update IPFS and runs via the command
npm run upload
That file is below. For my version that I used in svelte I simplified the file by removing all the file management and just loading a variable instead of a file (as in the example below)
const fs = require('fs');
const path = require('path');
const fleek = require('#fleekhq/fleek-storage-js');
require('dotenv').config()
const apiKey = process.env.FLEEK_API_KEY;
const apiSecret = process.env.FLEEK_API_SECRET;
const testFunctionUpload = async (data) => {
const date = new Date();
const timestamp = date.getTime();
const input = {
apiKey,
apiSecret,
key: `file-${timestamp}`,
data,
};
try {
const result = await fleek.upload(input);
console.log(result);
} catch(e) {
console.log('error', e);
}
}
// File management not used a my svelte version to keep it simple
const filePath = path.join(__dirname, 'README.md');
fs.readFile(filePath, (err, data) => {
if(!err) {
testFunctionUpload(data);
}
})

Facing issue while download file from sharepoint in node.js using sp-download npm package

I am using sp-download to download file from sharepoint in node js. I am executing the below code -
const Download = require('sp-download').Download;
let authContext = await spauth.getAuth(CONFIG.SHAREPOINT.SITES_LINK, {
username: CONFIG.SHAREPOINT.CREDS.USERNAME,
password: CONFIG.SHAREPOINT.CREDS.PASSWORD
});
const download = new Download(authContext);
let filePathToDownload = CONFIG.SHAREPOINT.SITES_LINK + 'sharePointFile File Path';
let saveToPath = 'localFile Path';
download.downloadFile(filePathToDownload, saveToPath)
.then((savedToPath) => {
return true;
})
.catch((error) => {
console.log("error", error);
return false;
});
But code will result below error -
"Error while resolving authentication class"
Any one have any idea?
I've been struggling with it as well and ended up debbuging node_modules/node-sp-auth/lib/src/auth/AuthResolverFactory.js where the error comes from.
Using Office 365 login and pass it should be enough to set authContext as simple object.
const username = CONFIG.SHAREPOINT.CREDS.USERNAME;
const password = CONFIG.SHAREPOINT.CREDS.PASSWORD;
const download = new Download({username, password});
In your case.

Is there a way that I can get git origin branch code by nodejs

I added a git hook in my project when push event is triggered.
When hook is triggered and the ref value is refs/heads/master, the prod index.html file will be updated.
I want to read the new index.html content
router.post('/gitHook', async (ctx, next) => {
const body = ctx.request.body;
const matches = body.ref.match(/^refs\/heads\/(.*)/);
const branchName = matches[1];
console.log(branchName);
if(branchName === 'master'){
console.log('should get new code from git origin master')
}
await next();
});
I got the index.html content using gitlab package.
const { Gitlab } = require('gitlab');
const api = new Gitlab({
host: 'myhost',
token: 'myToken',
});
api.RepositoryFiles.show(body.project_id, '/build/index.html', body.ref).then(res => {
const content = res.content;
const stringContent = new Buffer(content, 'base64').toString();
console.log(stringContent);
});

How to connect VPN using nodejs in ubuntu

I have the code in my nodejs file which gives me the following information
host:"147.0.40.145"
method:"aes-256-cfb"
password:"9c359ad1ebeec200"
port:38473
I need to use above information and want to connect VPN through it. I have used below code to extract the above information.
const connectServer = (serverId) => {
const token = store('access_token')
httpOptions.Authorization = token.token_type+' '+token.access_token
return new Promise((resolve, reject) => {
const response = await axios.post(`${baseUrl}/servers/${serverId}/connect`, {'serverId':serverId},{headers: httpOptions})
console.log(response.data)
resolve(response.data)
})
}
So I need to know whether it is possible using nodejs to connect or create VPN?
Thank you in advance!!!
Install this npm
npm i node-openvpn --save
const openvpnmanager = require('node-openvpn');
const opts = {
host: '147.0.40.145',
port: 38473,
timeout: 1500, //timeout for connection - optional, will default to 1500ms if undefined
logpath: 'log.txt' //optional write openvpn console output to file, can be relative path or absolute
};
const auth = {
user: '{{add user name}}',
pass: '9c359ad1ebeec200',
};
const openvpn = openvpnmanager.connect(opts)
openvpn.on('connected', () => {
console.log("Connected to VPN successfully...");
});
For more info , please read this link
Another option
Link

Categories