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

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'));

Related

What is "({})" in JavaScript?

I am learning JavaScript / Node.js. Looking at bot.js from botkit-starter-web line 33, it shows:
var db = require(__dirname + '/components/database.js')({});
My question is, what is ({}) represent in that line? I can't Google the answer for it.
require(...) is used to load a module, the return value of require is the module, which can be any javascript value (depends on the module being loaded).
In this case it is presumed to be a function.
Adding ({}) is calling that function and passing an empty object {} as the first and only argument.
The return value of that function call, being stored in the variable db.
It is equivalent to doing this:
var database = require(__dirname + '/components/database.js');
var db = database({});
At the first you know in database.js exists this code :
module.exports = function (object) {
// . . .
// some thing on object
return object;
};
when you require this JS file you can send to above function object data (empty or not empty)
var db = require(__dirname + '/components/database.js')({});
When a module is loaded ( In other words load a javascript file using require(..) ), it returns whatever is assigned to module.exports, for example
//javascript file add.js
module.exports = function(a,b){
return a+b;
}
//Usage in app.js
var add = require("add.js");
var result = add(2+2);//result would be 4
//Similarly
var result = require("add.js")(2+2);//result would be 4
In your case database.js returns a function in its module.exports and that function takes one paramter which is an object.
var db = require(__dirname + '/components/database.js')({});
In the above snippet you are passing an empty object to the function.The creators of database.js have given you options to customize some values, something like this
var db = require(__dirname + '/components/database.js')({
port:3306,
});
//or
var options = {};
options.port = 3306;
var Database = require(__dirname + '/components/database.js')
var db = Database(options);

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;

app.get('') is not working in node js with query parameters

Iam trying to provide a new route for my conversation application where it should accept the parameters passed along with the route should be accepted and can be used in client side.But I couldnt figure out why basic .get() is not working ,where Iam unable to render the html.
'use strict';
var express = require('express'); // app server
var bodyParser = require('body-parser'); // parser for post requests
var Conversation = require('watson-developer-cloud/conversation/v1'); // watson sdk
var bodyParser = require('body-parser');
var app = express();
app.use(express.static('./public')); // load UI from public folder
app.use(bodyParser.json());
app.get('/:id',function(req,res){
var userid = req.params.id;
var pid = req.query.pid;
res.sendFile(__dirname,'/public/index.html');
});
module.exports = app;
On my localhost:3000 index file is getting loaded but for something like localhost:3000/3405?pid=CBM it is not loading.
Then I have a js file on client side which would require these two values id and pid.For now I just hardcoded.But how can I use these values to client side js file..Can someone help me how can I do this...
Thanks
Updated :Adding my client side js file
var Api = (function() {
var messageEndpoint = '/api/message';
var emp = {
"pid": "CBM",
"id": "3405",};
return {
sendRequest: sendRequest,
modifytext: function(intent, text) {
if (intent == "Hello") {
console.log(text, "Inside intent");
for (var key in emp) {
var tempKey = '{{' + key + '}}';
var tempValue = emp[key];
text = replace(text, tempKey, tempValue);
console.log("came back");
}
}
return text;
console.log(text,"Final text");
}
};
function replace(text, originalString, replaceText) {
console.log("Reached replace functions", text, originalString, replaceText);
if (replaceText)
text = text.replace(originalString, replaceText);
else
text = text.replace(originalString, "");
return text
}
}());
This is incorrect:
res.sendFile(__dirname,'/public/index.html');
It should be this:
res.sendFile(__dirname + '/public/index.html');
Or (a bit more robust):
const path = require('path');
...
res.sendFile(path.join(__dirname, 'public/index.html'));
As a side note: apparently, if you pass a directory name to res.sendFile(), it will send back a 404 response. Not sure that the rationale behind that is.

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;

Send and get data with socket.io with an other javascript file nodejs and express

Lets say I have a JavaScript file that needs to communicate with other JavaScript file. So I could use this data in different javascript file.
In this case I have a game_server.js. In the gameserver.js I have two variables which I would like to use in the gamecore.js
var host // host of the game
var client // client that had joined the game
I would like to send them to the socket.io in de app.js and then use this variables in the game_core.js. So I can have data about the host and the client.
In the gamecore class i would like to have something like this
game_core.prototype.getPlayerInformation = function(data) {
this.host = data.host
this.client = data.client
}
It is all about getting information from the serverside to the clientside and the best way to do it is trough socket.io but i really don't know how
Also in the game_server script there is a instance for a game
game_server.createGame = function(player) {
//Create a new game instance
var thegame = {
id : UUID(), //generate a new id for the game
player_host:player, //so we know who initiated the game
player_client:null, //nobody else joined yet, since its new
player_count:1 //for simple checking of state
};
In the game_core the instance of a game is declared
var game_core = function(game_instance) {
//Store the instance, if any
this.instance = game_instance;
}
So it should be possible to get the player_host and player_client?
server.js
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(80);
var Game_core = function(){}
Game_core.prototype.getPlayerInformation = function(data)
{
this.host = data.host
this.client = data.client
return {host: this.host, client: this.client}
}
var game_core = new Game_core()
io.sockets.on('connection', function (socket) {
socket.emit('login', game_core.getPlayerInformation);
});
client.js
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('login', function(data){
console.log(data); // {host: xx, client: xx}
})
</script>

Categories

Resources