Nodejs require file depends on each other - javascript

Is it normal to have require for each other in both files? I have a requirement where AWS.js is managed in a separate file but AWS.js needs variable from index.js and index.js imports AWS.js.
As you see in the below example, I might have to include require for each other. Any solution to this?
index.js:
I can't move these variables to AWS.js because the event.Records[0].Sns.Message belongs to a function in index.js
var AWS = require('./AWS.js');
var sns = JSON.parse(event.Records[0].Sns.Message);
var sns_MetricName = sns.Trigger.MetricName;
var sns_NameSpace = sns.Trigger.Namespace;
AWS.js:
if(sns_NameSpace == "AWS/S3") {
keyFilter = ["BucketName", "StorageType"]
}
Workaround is to have both require each other. Any solution to this? Is this normal approach?
index.js:
var AWS = require('./AWS.js');
var sns = JSON.parse(event.Records[0].Sns.Message);
var sns_MetricName = sns.Trigger.MetricName;
var sns_NameSpace = sns.Trigger.Namespace;
exports.sns = sns;
exports.sns_MetricName = sns_MetricName;
exports.sns_NameSpace = sns_NameSpace;
AWS.js:
var index = require('./index.js');
if(index.sns_NameSpace == "AWS/S3") {
keyFilter = ["BucketName", "StorageType"]
}

Inject your dependencies. If AWS requires sns_NameSpace give it sns_NameSpace, don't import index:
AWS.js:
var keyFilter;
function init (sns_NameSpace) {
if(sns_NameSpace == "AWS/S3") {
keyFilter = ["BucketName", "StorageType"]
}
}
exports.init = init;
exports.keyFilter = keyFilter;
index.js:
var AWS = require('./AWS.js');
var sns = JSON.parse(event.Records[0].Sns.Message);
var sns_MetricName = sns.Trigger.MetricName;
var sns_NameSpace = sns.Trigger.Namespace;
AWS.init(sns_NameSpace); // <------- Pass the value HERE!!
console.log(AWS.keyFilter); // <---- Prints ["BucketName","StorageType"]
exports.sns = sns;
exports.sns_MetricName = sns_MetricName;
exports.sns_NameSpace = sns_NameSpace;

Related

How to pass variable to other modules with NodeJS?

I want to pass my logServiceClient object to all other modules included in server.js file. When I run below code it prints empty object;
logServiceClient{}
Is there any way to pass logServiceClient to all other included modules?
server.js file;
....
const logger = new Logger({
level: new CLevel('warn'),
ordered
})
var logServiceClient = require('./app/logServiceClient')(logger)
var userHandler = require('./app/userHandler')(logServiceClient)
userHandler file;
module.exports = function(logServiceClient){
console.log('logServiceClient' + JSON.stringify(logServiceClient))
}
There a many ways to inject without pulling in the logger from your other modules.
Use a factory to indirectly create and initialize your objects/modules
function factoryCreateModule() {
var client = require('client')
client.$logger = require('logger')
}
function factoryRequireModule(module) {
var client = require(module)
client.$logger = require('logger')
}
var client = factoryCreateModule()
client.logger.log('hello')
var client2 = factoryRequireModule('client')
client2.logger.log('hello')
Add your logger to all objects using prototype
Of course you can narrow down the target object...
var logger = {
log(message) {
console.log(message)
},
warn(message) {
console.log('!!! ' + message)
}
}
Object.prototype.$logger = logger
var x = 12;
x.$logger.log('I am a number')
var str = "Hello"
str.$logger.warn('WARNING FROM STRING')
Make your logger global
global is the 'window' in the module system.
// just for snippit to run
window.global = {}
var logger = {
log(message) {
console.log(message)
}
}
// main module
global.$logger = logger
// client module
global.$logger.log('hello world')
Pass the logger into the constructor or init method
var logger = require('logger')
var client = require('client')(logger)
var client2 = require('client2')({logger})
var client3 = require('client3')
client3.init(logger)
// file1.js
var foo = "bar";
exports.foo = foo;
//file2.js
var myModule = require('./file1');
var foo = myModule.foo;

Google Drive + Script throws permissions error even through I'm owner and granted permission

I'm trying to create a basic script on a 12-hour timer trigger that loops through each of my Google Calendars by their ICAL URL, and downloads the ICAL for a folder on my Google Drive (for backup purposes). It throws this error
"No item with the given ID could be found, or you do not have permission to access it. (line 23, file "Code")" (Line #23 is var folder... )
Running the script does download and save the ICAL file on the first run through the loop (and if I manually pass in each unique ICAL URL one at a time), but the error then terminates the loop. Seeing as how I've authorized access already and am the owner of everything here, I'm not sure what else I need.
var calendarsToSave = [
"https://calendar.google.com/calendar/ical/inXXXXXXX.com/privateXXXX/basic.ics",
"https://calendar.google.com/calendar/ical/XXXXX.com_XXXXXXup.calendar.google.com/private-XXXXXXX/basic.ics"
];
var folder = '123xxxxxxxxv789'; // my gdrive folder
function downloadFile(calendarURL,folder) {
var fileName = "";
var fileSize = 0;
for (var i = 0; i < calendarsToSave.length; i++) {
var calendarURL = calendarsToSave[i];
var response = UrlFetchApp.fetch(calendarURL, {muteHttpExceptions: true});
var rc = response.getResponseCode();
if (rc == 200) {
var fileBlob = response.getBlob()
var folder = DriveApp.getFolderById(folder); // << returns a permissions error thus terminating the for loop
var file = folder.createFile(fileBlob);
fileName = file.getName();
fileSize = file.getSize();
}
var fileInfo = { "rc":rc, "fileName":fileName, "fileSize":fileSize };
return fileInfo;
} // end for loop
}
Updated: You are also re-initializing a variable that already exists from the parameters and as a global variable so we can remove the parameter if you want to keep the global variable.
We can also move the place where you get the Google Folder object. It stays the same every time so we don't need to retrieve it again.
var calendarsToSave = [
"https://calendar.google.com/calendar/ical/inXXXXXXX.com/privateXXXX/basic.ics",
"https://calendar.google.com/calendar/ical/XXXXX.com_XXXXXXup.calendar.google.com/private-XXXXXXX/basic.ics"
];
var folder = '123xxxxxxxxv789'; // my gdrive folder
function downloadFile(calendarURL) {
var fileName = "";
var fileSize = 0;
var gfolder = DriveApp.getFolderById(folder);
for (var i = 0; i < calendarsToSave.length; i++) {
var calendarURL = calendarsToSave[i];
var response = UrlFetchApp.fetch(calendarURL, {muteHttpExceptions: true});
var rc = response.getResponseCode();
if (rc == 200) {
var fileBlob = response.getBlob()
var file = gfolder.createFile(fileBlob);
fileName = file.getName();
fileSize = file.getSize();
}
var fileInfo = { "rc":rc, "fileName":fileName, "fileSize":fileSize };
return fileInfo;
} // end for loop
}
Let see where that gets us.
Your "folder" variable is outside the function, causing the data to be inaccessible to the "downloadFile" function.
Google apps coding seems to require variables to be in a function to be defined. I would recommend moving both "calendarsToSave" and "folder" to the inside of "downloadFile"
Here is an example that will return your error:
var folder = '1HSFBPfPIsXWvFEb_AalFYalkPwrOAyxD';
function myFunction() {
var folder = DriveApp.getFolderById(folder);
var name = folder.getName();
Logger.log(name);
}
And here is one that will return the file name:
function myFunction() {
var folder = '1HSFBPfPIsXWvFEb_AalFYalkPwrOAyxD';
var folder = DriveApp.getFolderById(folder);
var name = folder.getName();
Logger.log(name);
}

NodeJS - Require and Modules

Does require and module.exports in NodeJS could be used to obtain all functions in all JavaScript files residing in a directory rather than in a single JavaScript file? If so HOW? Could anyone please explain it with an example ?
If require is given the directory path, it'll look for an index.js file in that directory. So putting your module specific js files in a directory, creating an index.js file & finally require that directory in your working js file should do. Hope example below helps....
Example:
file: modules/moduleA.js
function A (msg) {
this.message = msg;
}
module.exports = A;
file: modules/moduleB.js
function B (num) {
this.number = num;
}
module.exports = B;
file: modules/index.js
module.exports.A = require("./moduleA.js");
module.exports.B = require("./moduleB.js");
file: test.js
var modules = require("./modules");
var myMsg = new modules.A("hello");
var myNum = new modules.B("000");
console.log(myMsg.message);
console.log(myNum.number);
By using require
you required the module in that file and you can use the all function of that prototype (single file ) not a complete directory.
e.g
function admin(admin_id)
{
//console.log(parent_id);
this.admin_id = admin_id;
}
//default constructor
function admin()
{
admin_id = null;
self =this;
}
//destructor
~function admin(){
this.admin_id = null;
console.log('admin obj destroyed!');
}
//exporting this class to access anywhere through data encapstulation
module.exports = admin;
//class methods
admin.prototype = {
help:function(params){
console.log('hi');
}
},
you can require this module and can use the function help
and by this method u can require all file (modules) in single file
Wiki: "Node.js is an open-source, cross-platform runtime environment for developing server-side Web applications.
Although Node.js is not a JavaScript framework, many of its basic modules are written in JavaScript, and developers can write new modules in JavaScript.
The runtime environment interprets JavaScript using Google's V8 JavaScript engine."
Nodejs example:
You have Afile.js
var Afile = function()
{
};
Afile.prototype.functionA = function()
{
return 'this is Afile';
}
module.exports = Afile;
And Bfile.js
var Bfile = function()
{
};
Bfile.prototype.functionB = function()
{
return 'this is Bfile';
}
module.exports = Bfile;
The Test.js file require Afile.js and Bfile.js
var Afile = require(__dirname + '/Afile.js');
var Bfile = require(__dirname + '/Bfile.js');
var Test = function()
{
};
Test.prototype.start = function()
{
var Afile = new Afile();
var Bfile = new Bfile();
Afile.functionA();
Bfile.functionB();
}
var test = Test;
test.start();

How to export functions from modules in node.js

I am using node.js (v4.2.2) with express (4.13.1). I am trying to import my custom module functions to another module. Application is created with express, and only thing added to app.js is require for my route var tests = require('./routes/tests'); and app.use for that route app.use('/tests', tests);
My two custom files (modules) are (path is relative to project root):
./model/test.js
./routes/tests.js
Here is ./model/test.js:
var id;
var testNumber1;
var testNumber2;
function Test(id, testNumber1, testNumber2) {
this.id = id;
this.testNumber1 = testNumber1;
this.testNumber2 = testNumber2;
};
exports.reset = function() {
this.testNumber1 = 0;
this.testNumber2 = 0;
};
module.exports = Test;
And here is ./routes/tests.js:
var express = require('express');
var Red = require('../model/test.js');
var router = express.Router();
/*create new test :id*/
router.post('/:id', function(req, res, next) {
var myNewTest = new Red(req.params.id, 0, 0)
myNewTest.testNumber2 += 1;
myNewTest.reset();
res.send('id: ' + myNewTest.id +
' testNumber2: ' + myNewTest.testNumber2);
});
module.exports = router;
When I try to execute curl -X POST http://localhost:3000/tests/1 i get error TypeError: myNewTest.reset is not a function. I am having trouble understanding how to export functions correctly. If I understand this api reference correctly, to expose constructor of module, i have to use module.exports = Test;, but that doesn't expose reset function. So, to expose it I have declared it like exports.reset = function() {...}, but obviously, that doesn't work, at least not in my case.
Through some other answers I have also seen function being declared normally function reset() {...}, and exposed like exports.reset = reset;, which gives me the same error.
How do I expose reset function properly?
You should add it to the prototype, at the moment it's just a static method in your module, not attached to the Test constructor.
function Test(id, testNumber1, testNumber2) {
this.id = id;
this.testNumber1 = testNumber1;
this.testNumber2 = testNumber2;
};
Test.prototype.reset = function() {
this.testNumber1 = 0;
this.testNumber2 = 0;
};
module.exports = Test;

loadContextGoodies is not defined

This is my pretty straight forward firefox plugin main.js. I run it and get 'loadContextGoodies is not defined', what is going wrong here?
const {Cc, Ci, Cu, Cr} = require("chrome");
var events = require("sdk/system/events");
var utils = require("sdk/window/utils");
var { MatchPattern } = require("sdk/util/match-pattern");
var pattern = new MatchPattern(/^https?:\/\/example\.com.*/);
function listener(event) {
var channel = event.subject.QueryInterface(Ci.nsIHttpChannel);
var url = event.subject.URI.spec;
if (isToBeRedirected(url)) {
channel.cancel(Cr.NS_BINDING_ABORTED);
var goodies = loadContextGoodies(channel);
var domWin = goodies.aDOMWindow;
var gBrowser = goodies.gBrowser;
var browser = goodies.browser;
var htmlWindow = goodies.contentWindow;
browser.loadURI("about:blank");
}
}
exports.main = function() {
events.on("http-on-modify-request", listener);
}
function isToBeRedirected(url) {
return pattern.test(url)
}
edit: I was totally overlooking the part of the source I used for the redirecting bit which contained the declaration of the function. I didnt notice it was a scrollbox.. Thanks for the answer though.
According to that answer : https://stackoverflow.com/a/22429478/1170900
You need to declare loadContextGoodies

Categories

Resources