Show a variable from one JS file to another JS file - javascript

I have a node.js controller that create a csv file and it is stored in a specific folder, there is also a value from a var called endpoint.
The thing is that in the end of the lines of the controller i have this start function to start another process in another javascript file called bot.js
const scrapeWebsite = require('../bot')
const start = new scrapeWebsite();
var endpoint ="192.186.1.1"
try {
start.init();
} catch (e) {
res.send(JSON.stringify(e, null, 5))
}
In the bot.js file i want to access the value of the endpoint variable of my controller.js to use it in the bot function process and i dont know how to do this.
like declare a new var in the bot.js with the same value as the endpoint in the controller.js
class scrapeWebsite {
init() {
this.startScrape()
}
async startScrape() {...}

Export that function from bot.js
module.exports.function_name = function_name
And when you want to run it in node.js controller, import it using
const {function_name} = require("../bot")
And when you want to execute that function, call that function
function_name(<with, arguments, from, bot.js, file>)

Related

Running python script from MagicMirror module

I am currently developing a custom module for my magic mirror.
I want this module to execute a python script.
This python script fetches data from a web server and creates a .json file in the module folder with the data.
I then want the module to import this datafile inside javascript and display it on screen.
However i cant get the magic mirror module to run the python script.
I have very little javascript knowledge so any help is appreciated.
This is the code i have so far
defaults: {
},
start: function () {
var timer = setInterval(()=>{
const spawn = require('child_process').spawn;
const childPython = spawn('python3', ['./modules/MMM-Test/bussavganger.py']);
this.updateDom()
}, 5000)
},
getDom: function() {
var element = document.createElement("div")
element.className = "myContent"
element.innerHTML = "Hello, everybody!"
return element
}
})
Currently i am just trying to run the module to see if the .json file is created. it is not.
If i run the python script separately the file is created, so i know the .py file is not the problem.
You tried calling the python script via your module's js file, but instead you should use to call the python script via the node_helper.js file.
So use the socketNotification function of the MagicMirror to call the noder_helper and in return the node_helper then calls your python script, you can do something with it and at the end send back a socketNotification to your module's js file, e. g. the result of your python program or the exit code, etc.
In your start: function() you could call the node_helper via this command, so that your python program is being started by the module helper later directly after booting up your module (doing that from now on every interval):
var self = this;
setInterval(function() {
self.sendSocketNotification('DO_PYTHON', <transmit data for your node_helper here>);
self.updateDom();
}, 5000);
Create a node_helper.js file in your module folder with the following:
var NodeHelper = require("node_helper");
const spawn = require("child_process").spawn;
module.exports = NodeHelper.create({
init() {
},
start() {
},
stop() {
},
// If notification of the main.js file is received, the node_helper will do this here:
socketNotificationReceived(notification, payload) {
if (notification === "DO_PYTHON") {
// this.config = payload;
this.yourOwnMethod();
} else {
// ...
}
},
yourOwnMethod() {
var self = this;
var process = spawn("python3", ["/absolute/path/to/modules/MMM-Test/bussavganger.py"]);
// do something else here
this.sendSocketNotification("PYTHON_DONE", <e. g. exit state as your payload>)
},
You can read in your json file with fs in the node_helper.js as well and parse it there and send it back via the sendSocketNotification.
Be sure to have included the two beginning lines in the node_helper.js and (!) important use always absolute paths.

how to pass a value from one javascript file into another javascript file

Currently, by using the "$.getScript" jquery method I am able to pass the pass parameters from one javascript file into another javascript file. For instance, this $.getScript call made on javascript file name "secondJavaScript.js" file to call the function name callMemoPage() from "firstJavaScript.js" file. I am passing the following "pageName", "acctNum" paramaters from "secondJavaScript.js" into "firstJavaScript.js" file. However, the issue how to get the value of the function "callMemoPage" into this "secondJavascript.js" file. And that value kept in variable "Memo" - which is in "firstJavaScript.js" file.
$.getScript('firstJavaScript.js', function(){
getMemo();
function getMemo(){
var pageName = "Memo Page"
var acctNum = "123"
// callMemoPage function located in "firstJavaScript.js" file
callMemoPage(pageName, acctNum)
console.log(Memo);
}
});
// firstJavaSctipt.js file
function callMemoPage(pageName, acctNum){
var Memo;
if(pageName == 'Memo Page') && (acctNum = '123'){
function(memoField){
var memoField = window.open("https://www.example.com");
// question how to pass the value of Memo into secondJavaScript.js file
Memo = $(memoField).find('input[name="MEMO"]').val();
}
}
}
You can write it to a JSON file using the fs module :
const fs = require('fs');
fs.writeFileSync('file.json', JSON.stringify(yourVariable));
// Other file
const myVariable = require('file.json');
If these two pages are in the same origin: see https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy, you can store the result of Memo in a cookie and then access it in the second page
Let's say you have multiple functions in fileOne.js, and you want to use them in fileTwo.js.
well in HTML you import them like this:
<html>
...
<script src="fileOne.js">
<script src="fileTwo.js">
...
</html>
Notice that fileOne.js must be before fileTwo.js, so every variable in fileOne.js will be available in fileTwo.js.
That's because HTML is synchronous.

How to pass modules inputs while calling it from index.js file

I am building some custom plugins for a product that uses proprietary npm module to setup connection and perform an operation(read, write and submit) on mainframe emulator.
I am setting up connection in index.js file and want to pass terminal variable to separate module while calling it
index.js snippet
var terminal;
const mainframeTerminal =require(‘private_module’);
const accountDetailsModule =require('./src/accountDetails');
terminal = private_module.connect('11.11.11.1:789');
let screen = await terminal.status();
// expose module from index.js file so that it can be consumes in product
export.getAccountDetails = accountDetailsModule.getAccountDetails(terminal)
accountDetails.js
module.exports.getAccountDetails = async function(terminal){
//perform some operation with termianl var - passed from index file
return data;
}
I am getting below error
exports.getAccountDetails = accountDetailsModule.getAccountDetails is not a function.
I also need to pass data input but for the time being it's not required,
Would like to know how node.js function will understand mapping if I just need to pass anyone of input only.
Please throw some inputs, I am new to coding.
like this
index.js
const mainframeTerminal =require('private_module');
const accountDetailsModule = require('./src/accountDetails');
const terminal = private_module.connect('11.11.11.1:789');
let screen = await terminal.status();
// expose module from index.js
exports = accountDetailsModule(terminal);
accountDetails.js
const getAccountDetails = async (terminal) => {
// perform some operation
return data;
}
exports = getAccountDetails;
In CommonJS, modules are just a way to assign variables. So what you get in index.js when you require('./src/accountDetails') is exactly what you export in accountDetails.js (the value of getAccountDetails, which is an async function taking one argument).
runMyCode.js
Here's how you might call your code...
const mainframeTerminal =require('private_module');
const accountDetailsModule = require('./src/accountDetails');
const terminal = private_module.connect('11.11.11.1:789');
let screen = await terminal.status();
// run the code a print the result to console
accountDetailsModule(terminal).then(console.log);

Using module within module in NodeJS

I'm fairly new to nodejs. Writing my first application. I'm pretty used to php.
In order to keep code organized and clean, i always write functions in separate files and include them as required in php.
However, in nodejs i've had to require them like i would require a module.
For example.
functions.js
module.exports = {
check_db : function(key){
},
check_cache : function(key){
memcached.get(key,function(err, data){
console.log(data);
});
},
};
Included that in the main app like so
// Establish connection with cache and database
const mysql = require('mysql2');
const Memcached = require('memcached');
const memcached = new Memcached('localhost:11211');
const bb = require('bot-brother');
//Load the database cache functions
const dbc = require("./functions");
dbc.check_cache(123);
Now i can access the functions from dbc from the main app file, but i cannot use modules that have been required in the main app from the functions file.
I get an error that memcached is not defined.
How can i go about solving this?
Simple solution, you can require("memcached") in the functions.js file and create the server here. But I wouldn't go with this solution, as, if you need memcache somewhere else, you would have opened many connections on the memcache server.
Another, and cleaner solution IMO, is to inject the memcache dependency into your services (or functions as you call them). (this practice is called dependency injection if you want to learn about it and what are the benefits of it)
Here is how it would work:
you still create the memcache connection in the main file ;
instead of exporting a raw json object in your functions.js, you export a function that takes an argument (here memcache)
in your main file, you require that function and call it to get the service you want.
Here is what the code would look like:
main.js
//Load the database cache functions
const dbcFactory = require("./functions");
const dbc = dbcFactory(memcached)
functions.js
module.exports = function (memcached) {
return {
check_db : function(key){},
check_cache : function(key){
memcached.get(key,function(err, data){
console.log(data);
})
}
};

How to call a function both locally and externally in Node JS (called from two different files)

I have two files, let's call them main.js and sub.js, with a function in sub.js that is exported and called from the second file main.js but is also called from within sub.js (from another function that is exported).
The code is something like this:
Main.js:
var streak = require('./sub.js');
profile = streak.streak_broken(profile); // is called from another file
Sub.js:
// External functions
module.exports.streak_broken = function(profile) {
profile.counter = 0;
return profile;
};
module.exports.second_func = function(profile) {
// Do something
profile = streak_broken(profile); // streak_broken is not defined - how can I correct this?
return profile;
};
I could obviously make a copy of the streak_broken function and either have it as a local function further up in sub.js or put it directly into the module.exports.second_func code where it's called within sub.js but that isn't the best programming I guess.
How can I overcome that warning "streak_broken is not defined"? Your help is appreciated, thank you in advance!
Replace
profile = streak_broken(profile);
with
profile = module.exports.streak_broken(profile);

Categories

Resources