How to pass variable to other modules with NodeJS? - javascript

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;

Related

Nodejs require file depends on each other

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;

How to send JSON inside of class syntax to an API?

Let's say I have a normal mjs file and an API such as this:
// Storage.mjs
class Storage {
constructor(name, age) {
this.name = name;
this.age = age;
this.json = JSON.stringify(this);
}
}
var store = new Storage('eMart', 2);
// server.js
var express = require('express'),
fs = require('fs'),
data = fs.readFileSync('website/js/storage.mjs'),
convert = JSON.parse(data);
var app = express(),
server = app.listen(3000, initialize);
console.log(convert);
function initialize() {
console.log("Local Host Initialized.");
}
app.use(express.static('website'));
My goal is to send the JSON data to API which is inside of class syntax, but every time Node keeps throwing undefined and an error like this picture;
Most of people's question was sending data from API to specific js file which was totally opposite of my case. It was hard to find solution from there.
Are there any proper ways to pass JSON data to API?
I suppose this is what you want?
// assume this is loaded with fs.readFileSync
const mjs = `
class Storage {
constructor(name, age) {
this.name = name;
this.age = age;
this.json = JSON.stringify(this);
}
}
var store = new Storage('eMart', 2); // I assume you missed the quote here
`;
eval(mjs); // You can't just convert an js file into a JSON, you have to eval it first(not safe, use it with caution)
let result = JSON.parse(store.json); // Since the file outputs a variable called "store" and it has a "json" property
console.log(result);
The server.js snippet
// server.js
var express = require('express'),
fs = require('fs'),
data = fs.readFileSync('website/js/storage.mjs');
(0, eval)(data); // indirect eval
var convert = JSON.parse(store.json);
var app = express(),
server = app.listen(3000, initialize);
console.log(convert);
function initialize() {
console.log("Local Host Initialized.");
}
app.use(express.static('website'));

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;

Javascript object is a function

I want to create an Object in a new JS file from another JS file.
I get the following error, Object is not a function, in the new file:
var Bricklet = require('../Bricklet');
var b = new Bricklet("afea", "sdafdf", "affe");
console.log(b);
When I try to create an object in the JS file itself it works.
Here is the code:
var Bricklet = (function () {
function Bricklet(uid, deviceIdentifier, connectedUid) {
this._uid = uid;
this._deviceIdentifier = deviceIdentifier;
this._connectedUid = connectedUid;
}
return Bricklet;
})();
var bricklet = new Bricklet("afea", "sdafdf", "affe");
console.log(bricklet);
Why do I get this error?
You have to export the Bricklet function:
var Bricklet = (function () {
function Bricklet(uid, deviceIdentifier, connectedUid) {
this._uid = uid;
this._deviceIdentifier = deviceIdentifier;
this._connectedUid = connectedUid;
}
return Bricklet;
})();
var bricklet = new Bricklet("afea", "sdafdf", "affe");
console.log(bricklet);
module.exports = Bricklet; // <<------- Add this

Categories

Resources