How can i export variable to other files using nodejs? - javascript

I am new to nodejs i just want to bring data from event.js to app.js its in same directory but i could not get it working any idea how to make it work ?
app.js
var SnmpData = require('./event.js');
console.log('SNMP data',SnmpData);
event.js
var message = {
event: {
header: {
eventSource: "d-sms"
},
body: {
data: [
{
oid: "1.3.6.1.4.140.625",
host: "135.89.157.201",
port: "162",
value: "Problem with monitoring device",
type: ""
},
{
oid: "1.3.6.1.4.345.765",
host: "135.89.157.299",
port: "162",
value: "Problem with monitoring device-2",
type: ""
}],
message: "Activate Collaborate"
}
}
}
}

just add in the end of events.js this :
exports.message = message ;
Also take a look to node modules to understand how things work.

Related

Get User_ID from interactions in DiscordJS

I'm Currently Trying to get the user_id from the interaction.
This code will add command named 'test' that will give option 'testing' and when someone types '1' then it should show the channel_id that the command went from and also the user that did that command.
test.js :
module.exports = {
name: "test",
description: "example",
options: [
{
name: "testing",
description: "testing only.",
type: 3,
required: true,
},
],
async execute(_bot, say, interaction, args) {
let object1 = args[0].value;
if (object1 == '1') {
await say(interaction, 'Channel ID : ' + interaction.channel_id + '\nUser : '+ interaction.message.author.id);
}
else
{
return;
}
},
};
My Problem here that it's not getting the user.id in any way i have tried the following examples :
interaction.member.id;
interaction.user.id;
interaction.user_id;
interaction.member_id;
interaction.guildmember.id;
Noone of them works.
It should've been ;
interaction.member.user.id
Because it appeared in the log under member.

Patch request to COSMOS DB: 404 not found

Updated: Solved by Sajeetharan's suggestion! Thanks.
I'm trying to implement the api to partially update cosmos db. I got 404 not found when I tested this patch request. I tested query in cosmo's db, it's working as expected. I don't know which part is wrong.
You should invoke the Patch on the container as how you have done fetchAll request.
Here is a sample,
const multipleOperations: PatchOperation[] = [
{
op: "add",
path: "/aka",
value: "MeFamily"
},
{
op: "replace",
path: "/lastName",
value: "Jose"
},
{
op: "remove",
path: "/parents"
},
{
op: "set",
path: "/address/zip",
value: 90211
},
{
op: "incr",
path: "/address/zip",
value: 5
}
];
const { resource: patchSource2 } = await container.item(patchId!).patch(multipleOperations);

Protractor Cucumber Configuration file throwing undefined warning for my scenarios even though those are present

my Configuration file is not able to find the spec file even though it is present in the path that i provided in the cucumberOpts..i tried all the resolutions but none of them is worked.
Config File
const log4js = require('log4js');
var fs=require('fs');
global.screenshots = require('protractor-take-screenshots-on-demand');
global.browser2;
var propertiesReader=require('properties-reader');
var env=require("../../env.js");
const {Given, Then, When, Before} = require('cucumber');
exports.config = {
//seleniumAddress: 'http://localhost:4444/wd/hub',
directConnect:true,
framework: 'custom',
// path relative to the current config file
frameworkPath: require.resolve('protractor-cucumber-framework'),
capabilities: {
'browserName': 'chrome',
metadata: {
browser: {
name: 'chrome',
version: '79'
},
device: 'MacBook Pro 15',
platform: {
name: 'OSX',
version: '10.12.6'
},
disableLog:true,
durationInMS:true,
openReportInBrowser:true
}
},
ignoreUncaughtExceptions:false,
// Spec patterns are relative to this directory.
specs: [
'../../Test_modules/features/'
],
beforeLaunch:function(){
if (fs.existsSync('./logs/ExecutionLog.log')) {
fs.unlink('./logs/ExecutionLog.log')
}
log4js.configure({
appenders: {
out: { type: 'console' },
info:{ type: 'dateFile', filename: "../Reports/logs/info", "pattern":"-dd.log",alwaysIncludePattern:false},
"console" : {
"type": "console",
"category": "console"
},
"file" : {
"category": "test-file-appender",
"type": "file",
"filename": "../../Reports/logs/log_file.log",
"maxLogSize": 10240,
// "backups": 3,
// "pattern": "%d{dd/MM hh:mm} %-5p %m"
}
},
categories: {
"info" :{"appenders": ["console"], "level": "info"},
"default" :{"appenders": ["console", "file"], "level": "DEBUG"},
//"file" : {"appenders": ["file"], "level": "DEBUG"}
}
});
},
cucumberOpts: {
require:['../../Test_modules/utilities/timeOutConfig.js','../../Test_modules/stepDefinition/spec.js'],
tags: false,
profile: false,
format:'json:../../Reports/jsonResult/results.json',
'no-source': true
},
onPrepare: function () {
const logDefault = log4js.getLogger('default');
const logInfo=log4js.getLogger('info');
screenshots.browserNameJoiner = ' - '; //this is the default
//folder of screenshot
screenshots.screenShotDirectory = '../../Screenshots';
global.openNewBrowser=require('../../Test_modules/utilities/newBrowserinstance.js');
global.testData=require('../../TestData/testData.json');
browser.logger = log4js.getLogger('protractorLog4js');
global.firstBrowser=browser;
global.properties=propertiesReader('../../TestData/propertyConfig.properties');
browser.waitForAngularEnabled(false);
browser.manage().window().maximize();
global.facebook=require('../../Test_modules/pages/fbPageObjects.js');
global.utility=require('../../Test_modules/utilities/testFile.js');
},
plugins: [{
package: 'H:/workspace/Proc-UI/node_modules/protractor-multiple-cucumber-html-reporter-plugin',
options:{
// read the options part for more options
automaticallyGenerateReport: true,
removeExistingJsonReportFile: true,
reportPath:'../../Reports/HtmlReports',
reportName:"test.html"
},
customData: {
title: 'Run info',
data: [
{label: 'Project', value: 'Framework Setup'},
{label: 'Release', value: '1.2.3'},
{label: 'Cycle', value: 'Test Cycle'}
]
},
}]
};
Spec File
var utilityInit,page2;//browser2;
page1=new facebook(firstBrowser);
module.exports=function(){
this.Given(/^Open the browser and Load the URL$/,async function(){
await firstBrowser.get(properties.get("url1"));
browser.logger.info("Title of the window is :"+await browser.getTitle());
//screenshots.takesScreenshot("filename");
});
this.When(/^User entered the text in the search box$/,async function(){
firstBrowser.sleep(3000);
await page1.email().sendKeys(testData.Login.CM[0].Username);
browser.sleep(3000);
await page1.password().sendKeys(testData.Login.CM[0].Password);
});
this.Then(/^click on login button$/,async function(){
browser.sleep(3000);
await facebook.submit().click();
});
this.Then(/^User tried to open in new browser instance$/,async function(){
browser2=await openNewBrowser.newBrowserInit(firstBrowser);
utilityInit=new utility(browser2);
utilityInit.ignoreSync(properties.get("url2"));
browser2.manage().window().maximize();
console.log(await utilityInit.title()+" title");
browser2.sleep(5000);
});
this.When(/^User entered the text in the email field$/,async function(){
page2=new facebook(browser2);
console.log(await page2.title()+" browser2");
await page2.search().sendKeys("testing");
browser2.sleep(3000);
page1=new facebook(firstBrowser);
console.log(await page1.title()+" browser1");
await page1.email().sendKeys(testData.Login.CM[0].Username);
screenshots.takeScreenshot("newScreenshot");
firstBrowser.sleep(5000);
});
};
Execution log
1) Scenario: Title of your scenario # ..\features\test.feature:24
? Given Open the browser and Load the URL
Undefined. Implement with the following snippet:
Given('Open the browser and Load the URL', function () {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
? Then User tried to open in new browser instance
Undefined. Implement with the following snippet:
Then('User tried to open in new browser instance', function () {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
? And User entered the text in the email field
Undefined. Implement with the following snippet:
Then('User entered the text in the email field', function () {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
√ After # ..\..\node_modules\protractor-cucumber-framework\lib\resultsCapturer.js:27
1 scenario (1 undefined)
3 steps (3 undefined)
0m00.004s
i tried by adding cucumber dependencies, updating from relative path to absolute path everything i did.. but none it is resolved.. previously it worked fine but in the process of updating it in to public framework file.. i updated the paths from absolute to relative path. that's it i lost my whole framework and it is continuesly saying undefined scenarios.
**For Just made me sure i ran the script by passing wrong spec file name in the cucumber opts and still it giving Undefined and that confirmed me that it is not even considering that spec file that i passed.
Simple installation makes my framework works
npm install cucumber#1.3.3 --save-dev

Get message_id from Telegram message - node.js

I have a problem concerning a Telegram bot I am currently working on. I get messages from users in the following format:
update { update_id: 82618016,
message:
{ message_id: 363,
from: { id: 22303518, first_name: 'Steve', language_code: 'de-DE' },
chat: { id: 22303518, first_name: 'Steve', type: 'private' },
date: 1501501753,
text: 'j' } }
When I want to access the id of the chat I can do this without any problems by using
$.message.chat.id
As soon as a want to get the message_id or first_name I only get "undefined".
$.message.chat.first_name
$.message.message_id
Can anyone help me here? As far as I see it I understood the structure of the message correctly so I don't really know what's the problem here.
Thank you very much in advance
EDIT: I am adding a bit more of my code here:
The main code for the bot (including the webhook) is this:
initializeBot();
function initializeBot(){
const Telegram = require('telegram-node-bot');
const PingController = require('./controllers/ping');
const OtherwiseController = require('./controllers/otherwise');
const tg = new Telegram.Telegram('MY_TOKEN_IS_HERE', {
webhook: {
url: 'https://xxx.herokuapp.com',
port: process.env.PORT || 443,
host: '0.0.0.0'
}
})
tg.router.when(new Telegram.TextCommand('/ping', 'pingCommand'), new PingController())
.otherwise (new OtherwiseController());
}
When the OtherwiseController gets called the following code is called (I reduced it to the essentials to clarify the problem.
class OtherwiseController extends Telegram.TelegramBaseController {
handle($){
console.log($.message.chat.first_name);
console.log($.message.text);
console.log($.message.chat.id);
console.log($.message.message_id);
}
}
The console output for this message
update { update_id: 82618020,
message:
{ message_id: 371,
from: { id: 22303518, first_name: 'Steve', language_code: 'de-DE' },
chat: { id: 22303518, first_name: 'Steve', type: 'private' },
date: 1501509762,
text: 'hello' } }
would be:
undefined
hello
22303518
undefined
Use the below method to extract the keys of your json object, then you can access with an appropriate key:
Object.keys($.message.chat);

How to Set a Series of setHeader's DRY

I'm just learning to use the DRY principle and I can't figure how to set a series of setHeader's DRY (if at all possible??).
Any help is appreciated.
function plugin(options) {
var defaults = {
cache: 0
, port: 8080
, host: 'localhost'
, verbose: false
, serverInfo: 'myserver'
, cacheControl: 'no-store'
, xPowerBy: 'Locomotion'
, xFrameOptions: 'DENY'
, xXSSProtection: '1; mode=block'
, xContentTypeOption: 'nosniff'
, contentSecurityPolicy: 'default-src "self"'
};
var opts = options || {};
setDefaults(opts, defaults);
return function(files, staticsmith, done) {
if (server) {
done();
return;
}
// Some stuff
server = require('http').createServer(function (request, response) {
response.setHeader('X-Powered-By', opts.xPowerBy);
response.setHeader('x-frame-options', opts.xFrameOptions);
response.setHeader('X-XSS-Protection', opts.xXSSProtection);
response.setHeader('X-Content-Type-Options', opts.xContentTypeOption);
response.setHeader('Cache-Control', opts.cacheControl);
response.setHeader('Content-Security-Policy', opts.contentSecurityPolicy);
// Does some more stuff
};
}
This isn't a major/offensive violation of the DRY principal because you are setting the header for different options/values each time.
Checking the documentation, it doesn't seem there is an overload that accepts an array of objects or objects with multiple header properties.
However, if you want to improve the code visually(and completely remove duplication), you can take a 'data-driven' approach and use an array
var headers = [{
name: 'X-Powered-By',
option: opts.xPowerBy
}, {
name: 'x-frame-options',
option: opts.xFrameOptions
}, {
name: 'X-XSS-Protection',
option: opts.xXSSProtection
}, {
name: 'X-Content-Type-Options',
option: opts.xContentTypeOption
}, {
name: 'Cache-Control',
option: opts.cacheControl
}, {
name: 'Content-Security-Policy',
option: opts.contentSecurityPolicy
}];
and then loop
for(var i = 0; i < headers.length; i++){
response.setHeader(headers[i].name, headers[i].option);
}

Categories

Resources