How to create JSON nested Objects using NodeJS and JSON.stringify() - node.js

My problem is in the port_password.
{
"server": "0.0.0.0",
"server_ipv6": "::",
"local_address": "127.0.0.1",
"local_port": 1080,
"timeout": 120,
"method": "aes-256-cfb",
"protocol": "origin",
"protocol_param": "",
"obfs": "tls1.2_ticket_auth",
"obfs_param": "",
"redirect": "",
"dns_ipv6": false,
"fast_open": true,
"workers": 1,
"port_password": "{\"10000\":\"pass\",\"10001\":\"pass\",\"10002\":\"pass\",}"
}
The code I used to generate JSON.
account.forEach(ssr => {
portsPasswords += JSON.stringify(ssr.port.toString()) + ':' + JSON.stringify(ssr.password.toString()) + ','
})
I want the output something like this. How can I achieve that using NodeJS and JSON.stringfy()?
{
"server": "0.0.0.0",
"server_ipv6": "::",
"local_address": "127.0.0.1",
"local_port": 1080,
"timeout": 120,
"method": "aes-256-cfb",
"protocol": "origin",
"protocol_param": "",
"obfs": "tls1.2_ticket_auth",
"obfs_param": "",
"redirect": "",
"dns_ipv6": false,
"fast_open": true,
"workers": 1,
"port_password": {
"10000":"pass",
"10001":"pass",
"10002":"pass"
}
}

reduce into an object instead:
const account = [
{ port: 10000, password: 'pass1' },
{ port: 10001, password: 'pass2' },
{ port: 10002, password: 'pass3' }
];
const port_password = account.reduce((a, { port, password }) => {
a[port] = password;
return a;
}, {});
const entireObj = {
"server": "0.0.0.0",
// etc
port_password
};
console.log(JSON.stringify(entireObj));

Related

Metamask is not connecting local network Localhost 8545

I'm building a Web-App using NodeJs. I'm stuck when I tried to connect the local server to metamask. When I try to add new network as mentioned in my. When I try to connect to localhost8545 in chrome extension then it returns this error:
trufle-config.js
var HDWalletProvider = require("truffle-hdwallet-provider");
module.exports = {
// See <https://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
networks: {
development: {
host: "127.0.0.1",
network_id: "*", // Match any network id
port: 8545,
//* gas: 8000000,
//* gasprice: 10000000000,
},
ropstenInfura: {
provider: function() {
return new HDWalletProvider(
process.env.INFURA_ROPSTEN_MNEMONIC,
"https://ropsten.infura.io/v3/" + process.env.INFURA_PROJECT_ID
);
},
network_id: "3",
},
ropstenLocal: {
from: "*********************",
host: "127.0.0.1",
port: 8545,
network_id: "*",
gas: 5000000,
gasPrice: 10000000000,
},
live: {
from: "*******************",
host: "127.0.0.1",
port: 8545,
network_id: "*",
gas: 500000,
gasPrice: 1000000000,
},
},
compilers: {
solc: {
version: "0.4.24",
},
},
};
Ganache-cli

Problem with app update yml files is not generated in electron?

I have a problem with the auto-update of electron app,
After I finished all the app parts and I am trying to push it to my custom update server , I found this error message in my logger :
Error unknown ENOENT: no such file or directory, open
'C:\{appPath}\{appName}\resources\app-update.yml'
and here is my package.json build configuration
"build": {
"appId": "com.server.app",
"copyright": "Copyright company name",
"generateUpdatesFilesForAllChannels": true,
"win": {
"target": "nsis",
"icon": "build/icon.ico"
},
"mac": {
"target": "dmg",
"artifactName": "appName.dmg",
"icon": "build/icon.icns"
},
"dmg": {
"background": "build/i-bg.tif",
"icon": "build/setup.icns",
"iconSize": 80,
"title": "${productName}-${version}",
"window": {
"width": 540,
"height": 380
}
},
"nsis": {
"artifactName": "${productName}-Setup-${version}.${ext}",
"oneClick": false,
"perMachine": false,
"allowToChangeInstallationDirectory": true,
"installerIcon": "build/setup.ico",
"uninstallerIcon": "build/setup.ico",
"installerHeader": "build/installerHeader.bmp",
"installerSidebar": "build/installerSidebar.bmp",
"runAfterFinish": true,
"deleteAppDataOnUninstall": true,
"createDesktopShortcut": "always",
"createStartMenuShortcut": true,
"shortcutName": "AppName",
"publish": [{
"provider": "generic",
"url": "https://my-update-server/path"
}]
},
"extraFiles": [
"data",
"templates"
]
},
"publish": [{
"provider": "generic",
"url": "https://my-update-server/path"
}],
and here is the code for triggering the auto-update
//-----------------------------------------------
// Auto-Update event listening
//-----------------------------------------------
autoUpdater.on('checking-for-update', () => {
splashLoadingStatus(`Checking for ${appName} update ...`);
})
autoUpdater.on('update-available',(info) => {
splashLoadingStatus(`${appName} new update available.`);
})
autoUpdater.on('update-progress',(progInfo) => {
splashLoadingStatus(`Download speed: ${progInfo.bytesPerSecond} - Download ${progInfo.percent}% (${progInfo.transferred}/${progInfo.total})`);
})
autoUpdater.on('error' , (error) => {
dialog.showErrorBox('Error', error.message);
})
autoUpdater.on('update-downloaded', (info) => {
const message = {
type: 'info',
buttons: ['Restart', 'Update'],
title: `${appName} Update`,
detail: `A new version has been downloaded. Restart ${appName} to apply the updates.`
}
dialog.showMessageBox(message, (res) => {
if(res === 0) {
autoUpdater.quitAndInstall();
}
})
})
.....
autoUpdater.setFeedURL('https://my-update-server/path');
autoUpdater.checkForUpdatesAndNotify();
.....
then when I am pushing the build it will do everything correct with the latest.yml file generating but after installing I found the app-update.yml is not there ...
If you have a problem with missing app-update.yml and dev-app-update.yml then paste the following code into index.js:
import path from "path"
import fs from "fs"
const feed = 'your_site/update/windows_64'
let yaml = '';
yaml += "provider: generic\n"
yaml += "url: your_site/update/windows_64\n"
yaml += "useMultipleRangeRequest: false\n"
yaml += "channel: latest\n"
yaml += "updaterCacheDirName: " + app.getName()
let update_file = [path.join(process.resourcesPath, 'app-update.yml'), yaml]
let dev_update_file = [path.join(process.resourcesPath, 'dev-app-update.yml'), yaml]
let chechFiles = [update_file, dev_update_file]
for (let file of chechFiles) {
if (!fs.existsSync(file[0])) {
fs.writeFileSync(file[0], file[1], () => { })
}
}
I fixed it by using autoUpdater.setFeedURL() before autoUpdater.checkForUpdates(). Below is the code snippet that works for github releases. Also, please make sure there is existing release in Github before running this code.
import { autoUpdater } from "electron-updater";
// ...
autoUpdater.setFeedURL({
provider: "github",
owner: "org",
repo: "repo",
});

Multiple Config in JSON for Node.js

I am not sure what to title my question.
Its been a adventure with node.js and a helpful person pointed me to ioredis. Currently I have:
var Redis = require("ioredis");
const DBConfig = require(__dirname+'/../Config.json');
var cluster = new Redis.Cluster([
{
port: 6001,
host: "10.0.0.6",
},
{
port: 6002,
host: "10.0.0.5",
},
{
port: 6003,
host: "10.0.0.4",
},
{
port: 6004,
host: "10.0.0.3",
},
{
port: 6005,
host: "10.0.0.2",
},
{
port: 6006,
host: "10.0.0.1",
},
]);
But to me this seems it would be better in a json config file like...
Config.json:
{
"configA" : "abc",
"someotherconfigB" : "Stuff",
"foo" : "bar"
}
{
"port": 6001,
"host": "10.0.0.6",
},
{
"port": 6002,
"host": "10.0.0.5",
},
{
"port": 6003,
"host": "10.0.0.4",
},
{
"port": 6004,
"host": "10.0.0.3",
},
{
"port": 6005,
"host": "10.0.0.2",
},
{
"port": 6006,
"host": "10.0.0.1",
},
}
I am so new and this I just not sure how to implement this without syntax errors.
var Redis = require("ioredis");
const DBConfig = require(__dirname+'/../Config.json');
var cluster = new Redis.Cluster([DBConfig.redis]);
I am not sure how to implement "var cluster = new Redis.Cluster([DBConfig.redis]);" properly
You should declare those settings in as an array under a key
{
"configA" : "abc",
"someotherconfigB" : "Stuff",
"foo" : "bar",
"redisCluster": [
{
"port": 6001,
"host": "10.0.0.6"
},
{
"port": 6002,
"host": "10.0.0.5"
},
{
"port": 6003,
"host": "10.0.0.4"
}
]
}
Then use that key to access that value inside the required config file.
const DBConfig = require('../Config.json');
const cluster = new Redis.Cluster(DBConfig.redisCluster);
First, you need to have a proper config file. Your file seems to contain some config information and node information. I would suggest:
Config.json file:
{
"configs": {
"configA": "abc",
"someotherconfigB": "Stuff",
"foo": "bar"
},
"nodes": [
{
"port": 6001,
"host": "10.0.0.6"
},
{
"port": 6002,
"host": "10.0.0.5"
},
{
"port": 6003,
"host": "10.0.0.4"
},
{
"port": 6004,
"host": "10.0.0.3"
},
{
"port": 6005,
"host": "10.0.0.2"
},
{
"port": 6006,
"host": "10.0.0.1"
}
]
}
Then your file should look like:
const Redis = require('ioredis');
const DBConfig = require(__dirname + '/Config.json');
const cluster = new Redis.Cluster(DBConfig.nodes);
Object.entries(DBConfig.configs).map(([key, value]) => {
cluster.set(key, value);
});
DBConfig.nodes it's already an array. No need to put brackets around it
Object.entries(DBConfig.configs) will give you an array of [key, value] pairs of your DBConfig.configs's properties
Resources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Laravel Echo Server can not be authenticated, got HTTP status 500

I've installed both Laravel echo server and Laravel echo client.
Following is the laravel-echo-server.json configuration.
{
"authHost": "http://taxation.com",
"authEndpoint": "/broadcasting/auth",
"clients": [
{
"appId": "APP_ID",
"key": "someKey"
}
],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": "127.0.0.1",
"port": "3000",
"protocol": "http",
"socketio": {},
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": ""
}
The following script listens for channel events. It builds fine with npm run dev.
import Echo from 'laravel-echo'
let token = document.head.querySelector('meta[name="token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
window.Echo = new Echo({
broadcaster: 'socket.io',
host: '127.0.0.1:3000',
reconnectionAttempts: 5
});
window.Echo.join('checked-in-1')
.listen('.user.checked_in', (e) => {
console.log(e);
});
When trying to listen for any event on start laravel-echo-server command. It keeps throwing Client can not be authenticated, got HTTP status 500.
Note :
I really didn't find anything helpful on laravel-echo-serve nor on google.
Any help will be appreciated a lot.
Laravel V5.4
Thanks
Just getting the issue because of CSRF token. Didn't passed the token to the echo.
window.Echo = new Echo({
broadcaster: 'socket.io',
host: '127.0.0.1:3000',
reconnectionAttempts: 5,
csrfToken: token.content <--
});

Still unable to connect one Openshift app to another Openshift app's MongoDB database

After following the advice presented here:
(OpenShift) Sharing MongoDB between Apps not possible anymore?
...which in a nutshell is this -> "You need to create the application as scalable, then add MongoDB for it to work correctly. MongoDB will then go onto it's own gear, with it's own ip address and port number (remember to use this port number, or nothing will work)."
...I am still unable to successfully connect my Node.js app to the MongoDB database living on another Node.js app in Openshift.
I have tried the following permutations of a host string that have been suggested:
localhost
128.xxx.xxx.xxx
[24 character hash]-myapp-mydomain.rhcloud.com
...all with the same result. No connection.
Here is the code that makes the call to setup the db connection...
dbProvider = function(host, port, user, pass) {
console.re.log("Attempting to create a DB instance...");
this.db = new Db(process.env.OPENSHIFT_MONGODB_EXTDB_DBNAME, new Server(host, port, { auto_reconnect: true }, {}));
console.re.log("created the DB instance...");
if(this.db!= null){
console.re.log("successfully connected to remote db %s at %s:%s",this.db,host,port);
this.db.open(function(error, db){
if(error){
console.re.log("error %s attempting to open the db at %s:%s",error,host,port);
}
else{
db.authenticate(user, pass, function(error, result) { //db.authenticate(user, pass, function(error, result)
if(error){
console.re.log("error %s attempting to connect to remote db at %s:%s using user %s",error,host,port,user);
}
else{
console.re.log("successfully connected to remote db at %s:%s using user %s",host,port,user);
}
});
}
});
}
else{
console.re.log("unable to connect to remote db at %s:%s",host,port);
}
}
The above code fails at the callback from the db.open() with a null error object.
Upon inspecting the this.db object we see the following:
{
"domain": null,
"_events": {},
"_maxListeners": 10,
"databaseName": "myDb",
"serverConfig": {
"domain": null,
"_events": {},
"_maxListeners": 10,
"host": "xxxxxxxxxxxxxxxxxxxxxxxx-myApp-myDomain.rhcloud.com",
"port": 12345,
"options": {
"auto_reconnect": true
},
"internalMaster": false,
"connected": false,
"poolSize": 5,
"disableDriverBSONSizeCheck": false,
"ssl": false,
"_used": true,
"_readPreference": null,
"socketOptions": {},
"logger": {
"error": "[Function]",
"log": "[Function]",
"debug": "[Function]"
},
"eventHandlers": {
"error": [],
"parseError": [],
"poolReady": [],
"message": [],
"close": [],
"timeout": []
},
"_serverState": "disconnected",
"_state": {
"runtimeStats": {
"queryStats": {
"m_n": 0,
"m_oldM": 0,
"m_oldS": 0,
"m_newM": 0,
"m_newS": 0,
"numDataValues": 0,
"mean": 0,
"variance": 0,
"standardDeviation": 0,
"sScore": 0
}
}
},
"recordQueryStats": false
},
"options": {},
"_applicationClosed": false,
"bsonLib": {
"Code": "[Function]",
"Symbol": "[Function]",
"BSON": "[Function]",
"DBRef": "[Function]",
"Binary": "[Function]",
"ObjectID": "[Function]",
"Long": "[Function]",
"Timestamp": "[Function]",
"Double": "[Function]",
"MinKey": "[Function]",
"MaxKey": "[Function]"
},
"bson": {},
"bson_deserializer": "[ Circular {bsonLib} ]",
"bson_serializer": "[ Circular {bsonLib} ]",
"_state": "disconnected",
"pkFactory": "[Function]",
"forceServerObjectId": false,
"safe": false,
"notReplied": {},
"isInitializing": true,
"auths": [],
"openCalled": false,
"commands": [],
"_callBackStore": {
"domain": null,
"_events": {},
"_maxListeners": 10,
"_notReplied": {}
},
"logger": "[ Circular {logger} ]",
"slaveOk": false,
"tag": 1460656848883,
"eventHandlers": {
"error": [],
"parseError": [],
"poolReady": [],
"message": [],
"close": []
},
"serializeFunctions": false,
"raw": false,
"recordQueryStats": false,
"reaperEnabled": false,
"_lastReaperTimestamp": 1460656848883,
"retryMiliSeconds": 1000,
"numberOfRetries": 60,
"reaperInterval": 10000,
"reaperTimeout": 30000
}
Note: The host, port, and databaseName fields have been modified for privacy.
This db object differs from a properly connecting db object by only two fields...
...both db.serverConfig._serverState and db._state equal 'connected' vs. 'disconnected'
Appreciate hearing from anyone that has successfully accomplished what I am trying to do.
Thanks!

Resources