how can i set the dns of the node js server? - javascript

I want to set the primary dns , secondary dns of node js server.
But i use 'setup' module , there are only dns , not secondary dns.
Like this
var setup = require('setup')();
var config = setup.network.config({
wlan0: {
auto: true, // start at Boot
dhcp: true, // Use DHCP
wireless: {
ssid: 'myWirelessName', // Wireless SSID
psk: 'mySuperPassword', // Password
}
},
eth0: {
auto: true,
ipv4: {
address: '192.168.1.20',
netmask: '255.255.255.0',
gateway: '192.168.1.1',
dns: '8.8.8.8'
}
}
});
how can i set primary dns and secondary dns of the node js?
I would appreciate your help.

Related

Trying connection mqtt in browser

I'm trying to get a mqtt connection on my browser with JS
I'm following this tutorial: https://emqx.medium.com/use-websocket-to-connect-to-mqtt-broker-9e7baf1aa773
So I've got this:
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
<script>
// Globally initializes an mqtt variable
const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)
const host = 'ws://broker.***.***.com:9883'
const options = {
keepalive: 60,
clientId: clientId,
username: '***',
password: '***',
protocolId: 'MQTT',
protocolVersion: 4,
clean: true,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
will: {
topic: 'WillMsg',
payload: 'Connection Closed abnormally..!',
qos: 0,
retain: false
},
}
console.log('Connecting mqtt client')
const client = mqtt.connect(host, options)
client.on('connect', () => {
console.log('Client connected:' + clientId)
// Subscribe
})
</script>
And in my browser I've got this error:
After some research, some people say that need to use certificate: https://github.com/eclipse/paho.mqtt.javascript/issues/187
So, I've got this :
<script src="../browserMqtt.js"></script>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
var options = {
keyPath: '../credentials/client-key.pem',
certPath: '../credentials/client-cert.pem',
rejectUnauthorized : false,
ca: ['../credentials/a-cert.pem'],
protocolId: 'MQTT',
username: '***',
password: '***',
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8)
};
var client = mqtt.connect('ws://broker.***.***.com:9883',options);
client.on('connect', function(){
console.log('Connected');
});
</script>
I've got the same error in browser ...
The broker conguration for mosquitto, it's like this :
allow_anonymous false
password_file /mosquitto/config/passwd
#TCP
listener 1883
socket_domain ipv4
#SSL
listener 8883
socket_domain ipv4
cafile /mosquitto/config/tls/ca/ca-cert.pem
certfile /mosquitto/config/tls/server/server-cert.pem
keyfile /mosquitto/config/tls/server/server-key.pem
tls_version tlsv1.2
socket_domain ipv4
#WSS
listener 9883
socket_domain ipv4
protocol websockets
cafile /mosquitto/config/tls/ca/ca-cert.pem
certfile /mosquitto/config/tls/server/server-cert.pem
keyfile /mosquitto/config/tls/server/server-key.pem
tls_version tlsv1.2
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log
log_timestamp_format %Y-%m-%dT%H:%M:%S
log_type all
I can't understand how can I solve it ? Thanks for your help
You can't use client side certs in the browser to authenticate the client (unless you load them into the browsers keystore, but even then I'm not convinced it will work unless there is only one cert/key for the browser to pick as javascript code won't normally prompt the user to pick the right one).
Also loading client certs over http from the server totally defeats the point of using a client cert as anybody can download them.
You need to remove all of the following from the options
keyPath: '../credentials/client-key.pem',
certPath: '../credentials/client-cert.pem',
rejectUnauthorized : false,
ca: ['../credentials/a-cert.pem'],
protocolId: 'MQTT',
Because the paths are meaningless in the browser (and for the reasons I mentioned earlier)
You should also be starting your broker URL with wss:// to make it clear you are trying to connect over secure WebSockets.

Using the node.js google cloud speech to text, how can I get the status of a current job?

I managed to trigger a job with:
const config = {
languageCode: 'en-US',
enableSpeakerDiarization: true,
audioChannelCount: 2,
enableSeparateRecognitionPerChannel: true,
useEnhanced: true,
profanityFilter: false,
enableAutomaticPunctuation: true,
};
const audio = {
uri: `gs://${filePath}`
}
const requestObj = {
config: config,
audio: audio
}
return speechClient.longRunningRecognize(requestObj)
I get back an object with a name. I want to use that with https://cloud.google.com/speech-to-text/docs/reference/rest/v1/LongRunningRecognizeMetadata (via the node.js package) to get the current status.
How do I do it?
return speechClient.longrunning.Operation()
Seems not to exist
Looks like you can do it with:
return speechClient.operationsClient.getOperation({ name: googleName })
This is not super well documented

How to use Windows authentication to connect to Sql express?

I have a .env file that contains the below and I am using tedious connection pool.
SQL_SERVER=localhost
SQL_UNAME=US\JENNY
SQL_PSWD=Windows password
SQL_DB=DatabaseName
But I am getting login failed error as shown below:
ConnectionError: Login failed for user 'US\JENNY'
Below is my dbconfig file
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
userName: process.env.SQL_UNAME,
password: process.env.SQL_PSWD,
server: process.env.SQL_SERVER,
options: {
instanceName: 'SQLEXPRESS',
encrypt: false,
database: process.env.SQL_DB,
rowCollectionOnDone: true,
useColumnNames: true // for easier JSON formatting
}
};
Not sure what version of Tedious you're using. I bring it up because userName and password have been moved into an authentication section, so your current config would get you a deprecation warning.
But if you are using a current version, the authentication section also has an authentication.type setting that you can set to ntlm. See http://tediousjs.github.io/tedious/api-connection.html#function_newConnection for details.
The following connection config works for a windows based login for me:
module.exports = {
server: process.env.SQL_SERVER,
options: {
instanceName: 'SQLEXPRESS',
encrypt: false,
database: process.env.SQL_DB,
rowCollectionOnDone: true,
useColumnNames: true
},
authentication: {
type: 'ntlm',
options: {
userName: process.env.SQL_UNAME,
password: process.env.SQL_PSWD,
domain: process.env.SQL_DOMAIN
}
}
}

Protractor E2E testing; Verifying account activation email

I am trying to create a script for email verification. I mean when we create an account on the site, then a verification mail will come to the given mail address and then we have to go to that mail and verify it(clicking on the link/or fetching the code). I tried this solution. But I have got stuck on the specific error.
This is code which I am trying.
describe("Sample test case", function () {
function getLastEmail() {
let deferred = protractor.promise.defer();
console.log("Waiting for an email...");
mailListener.on("mail", function(mail){
deferred.fulfill(mail);
});
return deferred.promise;
}
beforeAll(function () {
browser.waitForAngularEnabled(false);
browser.get("https://mail.google.com/mail/");
isAngularSite(false);
browser.sleep(3000);
});
it("should login with a registration code sent to an email", function () {
element(by.id("username")).sendKeys("MyemailID");
element(by.id("password")).sendKeys("mypassword");
element(by.id("loginButton")).click();
browser.controlFlow().await(getLastEmail()).then(function (email) {
expect(email.subject).toEqual("BillPledge Email Verification");
expect(email.headers.to).toEqual("support#billpledge.com");
// extract registration code from the email message
let pattern = /Registration code is: (\w+)/g;
let regCode = pattern.exec(email.text)[1];
console.log(regCode);
});
});
});
and this is my conf file.
// An example configuration file.
exports.config = {
// The address of a running selenium server.
// seleniumAddress: 'http://localhost:4444/wd/hub',
// if we are using protractor's webdriver-manager locally, you cannot use selenium Address
// If the webdriver-manager needs to start a local server, you can use
selenium: 'http://localhost:4445/wd/hub',
seleniumPort: 4445, // Port matches the port above
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
// Spec patterns are relative to the current working directly when
// protractor is called.
specs: ['./e2eTest/GmailTest.js'],
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 300000
},
allScriptsTimeout: 200000,
onPrepare: function () {
global.isAngularSite = function (flag) {
browser.ignoreSynchronization = !flag;
};
browser.driver.manage().window().maximize();
//To generate the report.
let HtmlReporter = require('protractor-beautiful-reporter');
jasmine.getEnv().addReporter(new HtmlReporter({
baseDirectory: 'Results/Report'
}).getJasmine2Reporter());
let reporter = new HtmlReporter({
baseDirectory: 'Results/Report'
});
let path = require('path');
new HtmlReporter({
baseDirectory: 'Results/Report'
, preserveDirectory: false
, cssOverrideFile: 'css/style.css'
, takeScreenShotsForSkippedSpecs: true
, screenshotsSubfolder: 'images'
, jsonsSubfolder: 'jsons'
, takeScreenShotsOnlyForFailedSpecs: false
, gatherBrowserLogs: true
, pathBuilder: function pathBuilder(spec, descriptions, results, capabilities) {
// Return '<browser>/<specname>' as path for screenshots:
// Example: 'firefox/list-should work'.
return path.join(capabilities.caps_.browser, descriptions.join('-'));
}
, metaDataBuilder: function metaDataBuilder(spec, descriptions, results, capabilities) {
// Return the description of the spec and if it has passed or not:
return {
description: descriptions.join(' ')
, passed: results.passed()
};
}
});
let MailListener = require("mail-listener2");
// here goes your email connection configuration
let mailListener = new MailListener({
username: "myemailid",
password: "mypassword",
host: "imap.gmail.com",
port: 993, // imap port
tls: true,
tlsOptions: {rejectUnauthorized: false},
mailbox: "INBOX", // mailbox to monitor
searchFilter: ["UNSEEN", "FLAGGED"], // the search filter being used after an IDLE notification has been retrieved
markSeen: true, // all fetched email willbe marked as seen and not fetched next time
fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`,
mailParserOptions: {streamAttachments: true}, // options to be passed to mailParser lib.
attachments: true, // download attachments as they are encountered to the project directory
attachmentOptions: {directory: "attachments/"} // specify a download directory for attachments
});
mailListener.start();
mailListener.on("server:connected", function () {
console.log("Mail listener initialized");
});
global.mailListener = mailListener;
},
onCleanUp: function () {
mailListener.stop();
},
};
But while executing the script I am getting following error. The error is:
Error: Please log in via your web browser:
https://support.google.com/mail/accounts/answer/78754 (Failure)
and
Failed: browser.controlFlow(...).await is not a function
I know I am doing some mistake but I am not able to figure out. So can anyone can help me in pointing out and solve it, not solve but at least some suggestion which can help in running this script perfectly.
Thanks
Try to use browser.wait(getLastEmail) instead of browser.controlFlow().await(getLastEmail()

Making .local resolve to IP address AND port (mdns)

I'm using the multicast-dns node module to attempt making this work.
Looking up custom.local in the browser gives me the console message I setup, but I'm unable to see my actual server running (which is doing so at localhost:12345, where 12345 is a dynamic number). I want to be able to see my local server when visiting custom.local. Is this possible?
Here's some code:
mdns.on("query", query => {
if (query.questions[0] && query.questions[0].name === "custom.local") {
console.log(query);
mdns.respond({
answers: [
{
name: "custom.local",
type: "SRV",
data: {
port: n.get("p"), // dynamic port
weight: 0,
priority: 10,
target: ip // local IP
}
}, {
name: "custom.local",
type: "A",
data: ip,
ttl: 300
}
]
});
}
});
EDIT: I can connect to my local server just fine, that wasn't an issue.
Quoting cfreak:
You can't put port numbers in DNS. DNS is only for looking up an IP by name. For your browser to see it by the name alone you need a proxy program in front of your service or you need to run the service itself on port 80. Port numbers really shouldn't be dynamic. You should specify it in the setup of your service.
That answers my question and offers next steps. Thanks!
UPDATE: Figured out what I was trying to do. Here's some code!
FOUND A SOLUTION, WOOP WOOP!
I'm using this module, but tweaked the source a bit (only because I have dynamic ports, because I feel like it).
/* jshint undef: true, unused: true, esversion: 6, node: true */
"use strict";
//
// G E T
// P A C K A G E S
import express from "express";
import http from "http";
import local from "./server/local";
const n = express();
n.get("/", (req, res) => {
res.send("Welcome home");
});
//
// L A U N C H
const server = http.createServer(n);
server.listen(0, () => {
const port = server.address().port;
local.add(port, "custom.local");
});
Hope this helps you as well, future Internet searcher! :D
Don't let negative folks on other SE sites bring you down. :virtual fist bump:

Categories