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);
Related
I have an Azure function and a file called configAPI.json which are located in the same folder as shown in the image below.
I want to read the latter with the following code based on this post How can i read a Json file with a Azure function-Node.js but the code isn't working at all because when I try to see if there's any content in the configAPI variable I encounter undefined:
module.exports = async function (context, req) {
const fs = require('fs');
const path = context.executionContext.functionDirectory + '//configAPI.json';
configAPI= fs.readFile(path, 'utf-8', function(err, data){
if (err) {
context.log(err);
}
var result = JSON.parse(data);
return result
});
for (let file_index=0; file_index<configAPI.length; file_index++){
// do something
}
context.log(configAPI);
}
What am I missing in the code to make sure I can read the file and use it in a variable in my loop?
functionDirectory - give you path to your functionS app then you have your single function
I think you should do:
const path = context.executionContext.functionDirectory + '\\configAPI.json';
In case you want to parse your json file you should have:
const file = JSON.parse(fs.readFileSync(context.executionContext.functionDirectory + '\\configAPI.json'));
PS. context has also variable functionName so other option to experiment would be:
const path = context.executionContext.functionDirectory +
+ '\\' +context.executionContext.functionName + '\\configAPI.json';
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'));
Working on an express project with a SQLite database.
I'm getting an Sequelize TypeError that I've been working on for hours but I'm coming up against a brick wall:
C:\-----\node_modules\sequelize\lib\sequelize.js:392
this.importCache[path] = defineCall(this, DataTypes);
^
TypeError: defineCall is not a function
at Sequelize.import (C:\----\node_modules\sequelize\lib\sequelize.js:392:32)
at C:\----\models\index.js:25:32
After doing some research, it appears that this could be caused when trying to import a non-sequelize object. Below is the problematic index.js file.
index.js:
var Sequelize = require('sequelize');
var config = {
dialect: 'sqlite',
storage: 'library.db'
};
var connection = new Sequelize(config);
var contents = fs.readdirSync(__dirname);
var db = {};
contents = contents.filter(function(file){
var currFileName = __filename.split('/');
var checkOne = file.substr(file.length - 3, 3) === '.js';
var checkTwo = file !== currFileName[currFileName.length - 1];
return checkOne && checkTwo;
});
contents.forEach(function(file){
var path = [__dirname, file].join('/');
var model = connection.import(path);
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName){
var model = db[modelName];
if(model.associate) {
model.associate(db);
}
});
module.exports = {
models: db,
connection: connection
};
I do not have any function called defineCall, any idea where the error is coming from?
This is indeed caused by importing a file that's not a Sequelize model. In my case, it was because my index.js was pulling in my test files as well as the models, which were in the same directory. Try adding another check like checkOne to exclude anything that ends with .test.js.
With the hint from the answer by #Floppy, I got to realise that it would be better if we stored those related files encapsulated in a folder.
For eg. make a folder named Models and store your index.js with all the models (eg. User model, photos model, etc) and then try.
Thanks.
Keep getting a error that I can't push a JSON object to a JSON array. Only changes I made was that I this function is in a different file and so I called it as a module.
index.js
var mods = require('../server/api/getUserMods.js');
var usernamePerms = [ 'settings', 'mod1', 'mod2' ]
console.log(mods.getUserMods(usernamePerms));
getUserMods.js
var fs = require('fs');
exports.getUserMods = function(input) {
var umkModules = '../umk_modules/';
var modules = '{"module":[]}';
var moduleParse = JSON.parse(modules);
for (i = 0; i < input.length; i++) {
console.log("Parsing: " + input[i]);
console.log("At: " + umkModules.concat(input[i],"/","module-view.json"));
console.log();
var readModule = JSON.parse(fs.readFileSync(umkModules.concat(input[i],"/","module-view.json"), 'utf8'));
console.log(readModule);
moduleParse['modules'].push(readModule);
};
modules = JSON.stringify(moduleParse);
return modules;
};
The function getUserMods takes a array strings and searches within a specified file path finding a file called module-view.json then appending it to the empty JSON array.
When ran, I get this...
moduleParse['modules'].push(readModule);
moduleParse['module'].push(readModule);
Your property is named module, not modules. And I'm not entirely sure why you'd use JSON when you can simply do:
var moduleParse = {
module:[]
}
I'm trying to use VersionOne JS SDK in Node.js (https://github.com/versionone/VersionOne.SDK.JavaScript). I'm simply downloading whole library, placing it alongside with my js file:
var v1 = require('./v1sdk/v1sdk.js');
var V1Server = v1.V1Server;
console.log(v1);
console.log(V1Server);
Unfortunately something seems wrong, the output I get after calling
node app.js
is:
{}
undefined
Can somebody point me what I'm doing wrong or check whether the sdk is valid.
Thanks!
You can see in the source where V1Server is defined, that it's a class with a constructor. So you need to use the new keyword and pass the arguments for your environment.
https://github.com/versionone/VersionOne.SDK.JavaScript/blob/master/client.coffee#L37
var server = new V1Server('cloud'); //and more if you need
Can you try the sample.js script that I just updated from here:
https://github.com/versionone/VersionOne.SDK.JavaScript/blob/master/sample.js
It pulls in the two modules like this:
var V1Meta = require('./v1meta').V1Meta;
var V1Server = require('./client').V1Server;
var hostname = "www14.v1host.com";
var instance = "v1sdktesting";
var username = "api";
var password = "api";
var port = "443";
var protocol = "https";
var server = new V1Server(hostname, instance, username, password, port, protocol);
var v1 = new V1Meta(server);
v1.query({
from: "Member",
where: {
IsSelf: 'true'
},
select: ['Email', 'Username', 'ID'],
success: function(result) {
console.log(result.Email);
console.log(result.Username);
console.log(result.ID);
},
error: function(err) { // NOTE: this is not working correctly yet, not called...
console.log(err);
}
});
You might have to get the latest and build the JS from CoffeeScript.
I think I was trying out "browserify" last year and that's how the "v1sdk.js" file got generated. But I'm not sure if that's the best approach if you're using node. It's probably better just to do it the way the sample.js file is doing it.
However, I did also check in a change to v1sdk.coffee which property exports the two other modules, just as a convenience. With that, you can look at sample2.js. The only different part there is this, which is more like you were trying to do with your example:
var v1sdk = require('./v1sdk');
var hostname = "www14.v1host.com";
var instance = "v1sdktesting";
var username = "api";
var password = "api";
var port = "443";
var protocol = "https";
var server = new v1sdk.V1Server(hostname, instance, username, password, port, protocol);
var v1 = new v1sdk.V1Meta(server);