Hello i try to read somethink from my sqlite in coffe.script when i wrote it JS it works well but now i got some problem
Coffee.script:
I am new in coffeescript and i am wondering what am i doing wrong... Any tips guys ? :)
app.get('/indeks',
(req, res)->
tab = []
i = 0
db = new sqlite3.Database("xxx.sqlite3")
tab = []
i=0
console.log("Jestem przed dbHandler")
db.each("SELECT yyy FROM zzz", #dbHandler, #dbFinal
dbHandler:(err, row)->
console.log("I am in handler dbHandler")
if err
console.log("Error: " + err)
else
tab.push(row)
console.log(row)
dbFinal:()->
console.log("I am in dbFinal")
console.log("Final: " + tab)
console.log("Response")
res.send(tab)
db.close()
)
)
Now code in JS:
app.get('/indeks', function (req, res, next) {
var db = new sqlite3.Database("xxx");
var tab = new Array();
var i=0;
function dbHandler(err, row){
if (err) {
console.log("Error: " + err);
} else {
tab.push(row);
console.log(row);
}
}
function dbFinal(){
console.log("Final: " + tab);
console.log("Response");
res.send(tab);
}
db.each("SELECT zzz FROM yyy", dbHandler, dbFinal);
db.close();
});
Did you look into the transpiled coffee code? When using something like dbHandler:(err, row)-> a JSON-Object with the property dbHandler is generated. This is why you cannot pass dbHandler and dbFinal to the db.each call. This only works when defining a class.
Additionally, you got an unmatched bracket in the line 10 and a bracket too much in the last two lines.
You should always check the compiled code (respectively check whether it even compiles). Here is a helpful site for this. There, you can even convert your JS code to coffeescript.
Related
Hello Im and new to coding and working on a Bot command where it takes user input and saves it to a text file. But upon loading it states "Uncaught TypeError: Cannot read property 'send' of null"
Some changers I've made looking at various things:
application = collected.array()[0].content;
when .content was there it would at least run a few times then crash with Uncaught TypeError: Cannot read property ‘content’ of undefined
let appString = "" + application originally was using toString() function
fs.appendFile(./see/letters(${fileSearch}).txt, appString + "\n", function (err) added $fileSearch because I thought having to many users saving to my local computer file was overwhelming it
Any help on this matter would be greatly appreciated as each thing I try keeps crashing it but all seem to be some Uncaught TypeError
module.exports = {
name: 'ocean',
description: 'Takes User Input and saves it as Text file letters.txt',
execute(message, args) {
let application = {}
let filter = (message) => !message.author.bot;
let options = {
max: 1,
time: 15000
};
message.member.send("Write something")
.then(dm => {
// After each question, we'll setup a collector on the DM channel
return dm.channel.awaitMessages(filter, options)
})
.then(collected => {
// Convert the collection to an array & get the content from the first element
application = collected.array()[0];
let fileSearch = Math.floor(Math.random() * 11) + 1
let appString = "" + application;
var fs = require('fs')
fs.appendFile(`./see/letters(${fileSearch}).txt`, appString + "\n", function (err){
if (err) {
} else {
}
})
// Ask the next question
console.log(application)
return message.member.send("Got it, It was recieved")
})
}
}
Good morning.
I was testing a little bit with your given code and I made some changes.
module.exports = {
name: 'ocean',
description: 'Takes User Input and saves it as Text file letters.txt',
execute(message, args) {
let application = {}
let filter = (message) => !message.author.bot;
let options = {
max: 1,
time: 15000
};
message.member.send("Write something")
.then(dm => {
// After each question, we'll setup a collector on the DM channel
return dm.channel.awaitMessages(filter, options)
})
.then(collected => {
// Convert the collection to an array & get the content from the first element
application = collected.array()[0].content;
let fileSearch = Math.floor(Math.random() * 11) + 1
let appString = "";
appString += application;
var fs = require('fs')
fs.appendFile(`./see/letters(${fileSearch}).txt`, appString + "\n", function (err) {
if (err) {
console.log(err);
}
})
// Ask the next question
console.log(application)
return message.member.send("Got it, It was recieved")
})
}
}
First I want to say that application = collected.array()[0].content; works absolutely fine for me, every time I used it.
Anyways I changed let appString = "" + application; into
let appString = "";
appString += application;
What that makes is, it creates a variable appString, which is a string because we initialized it with "". In the second line we fill the currently empty string with the content we get from application. You could display it also like this: appString = appString + application. This works because appString is empty and gets the value of application into the empty string. Now the string isn't empty anymore and contains the content from application. This is a common way to fill a string.
I also changed your if else statement
fs.appendFile(`./see/letters(${fileSearch}).txt`, appString + "\n", function (err){
if (err) {
} else {
}
})
into
fs.appendFile(`./see/letters(${fileSearch}).txt`, appString + "\n", function (err) {
if (err) {
console.log(err);
}
})
because you had the if else, but did nothing with it. Now if there is an error it gets printed out on your console.
I hope this is understable and helped with your problem.
Good Day,
I am trying to have Alexa say the results of a SQOL query, but I receive an error every-time try to include owner.name in the output.
this.t("CASEINFO",resp.records[0]._fields.casenumber, resp.records[0]._fields.subject,resp.records[0]._fields.priority,resp.records[0]._fields.owner.name);
. I believe this is because it has a "." in the name, but I am not sure how to escape the period so it reads it correctly.
Note if I don't put "resp.records[0]._fields.owner.name" into the script, everything works without issue. I know, this is the reason for the error.
This what I have tried...
1) this.t("CASEINFO",resp.records[0]._fields.casenumber, resp.records[0]._fields.subject,resp.records[0]._fields.priority,resp.records[0]._fields.[owner.name]);
2) this.t("CASEINFO",resp.records[0]._fields.casenumber, resp.records[0]._fields.subject,resp.records[0]._fields.priority,resp.records[0]._fields.owner//.name);
3)putting into a var (var casenumber = owner.name) and then using casenumber in the query.
Any help would be appreciated.
'CaseInformation': function () {
console.log("CaseInformation function");
if (preFunctions.call(this)) {
//const OwnerName = getSlotValue(this.event.request.intent.slots.caseowner_name.value);
var CaseInfo = this.event.request.intent.slots.case_info.value;
console.log(`CaseInfo: ${CaseInfo}`);
const accessToken = this.event.session.user.accessToken;
sf.query("select casenumber,subject, owner.name, status, priority, account.name, lastmodifieddate from case where casenumber='" + CaseInfo + "'", accessToken, (err, resp) => {
if (resp.records!="") {
if (resp.records) {
const output = this.t("CASEINFO",resp.records[0]._fields.casenumber, resp.records[0]._fields.subject,resp.records[0]._fields.priority,resp.records[0]._fields.owner.name);
this.emit(":ask", output, this.t("PROMPT")); ```
Square bracket notation:
this.t("CASEINFO",resp.records[0]._fields.casenumber, resp.records[0]._fields.subject,resp.records[0]._fields.priority,resp.records[0]._fields["owner.name"]);
(This is my first question here, I'm excited :))
2 files: index.js (what I'm using to connect to the mongo, find and toArray the data), and admin.ejs where I want to display the data (user records: username, first name, last name...).
index.js:
var db = MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err)
throw err;
db.collection("Users").find().toArray(function (err, result) {
var i, count;
for (i = 0, count = result.length; i < count; i++) {
myArr.push(result[i]);
}
myArr = JSON.stringify(myArr);
});
console.log(myArr); // just for testing
console.log("connected to the mongoDB !");
});
app.get('/', function (req, res) {
res.render('Admin', {
myVar: myArr
});
});
admin.ejs:
var myOtherVar = JSON.parse('<%-myVar%>');
In the broswer "view source code" I can see
var myOtherVar = JSON.parse('[{"_id":"567a6fd307200cb90f7af961","Username":"Yogev" ...
so I know that the data passes correctly, but any atempt to use it fails - the JS "see" it as object Object and not as an array...
What should I do?
You'll just need to use object notation to access the data.
console.log(myOtherVar[0].Username)
// Returns 'Yogev'
This way you send a object to the view
res.view('Admin',{ myVar : myArr});
This way you use it in the view
<h1> <%= myVar[0].property %></h1>
In this case you use <%= because <% does not print the returned value by the expression just after it.
first off : I'm new to node, and a relative programming beginner.
I'm trying to create a small web app with Express, whose only goal is to fetch and reformat data from a website that doesn't have an open API.
To do so, I've decided to learn about scraping, and that brought me to Cheerio and Request.
I'm using reddit as an example, to learn on. The end goal in this example is to gather the name and href of the posts on the front page as well as the url leading to the comments, then to go on that page to scrape the number of comments.
What follows is the route that is called on a GET request to / (please excuse the variable names, and the comments/console.logs, I got frustrated) :
/*
* GET home page.
*/
exports.index = function(req, res){
var request = require('request')
, cheerio =require('cheerio')
, mainArr = []
, test = "test"
, uI
, commentURL;
function first() {
request("http://www.reddit.com", function(err, resp, body) {
if (!err && resp.statusCode == 200) {
var $ = cheerio.load(body);
$('.thing', '#siteTable').each(function(){
var url = $('a.title', this).attr('href')
, title = $('a.title', this).html()
, commentsLink = $('a.comments', this).attr('href')
, arr = [];
arr.push(title);
arr.push(url);
arr.push(commentsLink);
mainArr.push(arr);
});
second();
};
});
}
function second() {
for (i = mainArr.length - 1; i >= 0; i--) {
uI = mainArr[i].length - 1;
commentURL = mainArr[i][uI];
console.log(commentURL + ", " + uI + ", " + i);
var foo = commentURL;
request(foo, function(err, resp, body) {
console.log("what the shit");
// var $ = cheerio.load(body);
// console.log(mainArr.length + ", " + commentURL + ", " + i + ", " + uI);
// var test = $('span.title', 'div.content').html();
console.log(test + ", "+ foo + ", " + commentURL + ", " + i + ", " + uI);
// mainArr[1][2] = test;
});
};
if (i<=0) {
res.render('index', {title: test});
};
}
first();
};
The function first(); works as intended. It puts the title, the href and url to the comments in an array, then pushes that array in a master array containing those data points for all of the posts on the front page. It then calls the function second();
Said function's goal is to loop through the master array (mainArr[]), then select all of the urls leading to comments (mainArr[i][uI]) and launch a request() with that url as first parameter.
The loop works, but during the second call of request() inside the second() function, everything breaks down. The variable i gets set permanently at -1, and commentURL (the variable that is set to the URL of the comments of the current post), is defined permanently as the first url in arrMain[]. There are also weird behaviors with arrMain.length. Depending on where I place it, it tells me that arrMain is undefined.
I have a feeling that I'm missing something obvious (probably to do with asynchronicity), but for the life of me, I can't find it.
I would be really greatful for any suggestions!
You are correct about your guess, it's the infamous "Javascript loop Gotcha". See here, for example, for an explanation:
Javascript infamous Loop issue?
Besides that, it seems that only your debug prints are affected. The commented code regarding var test ought to work.
Finally, the kind of language is frowned upon in SO, you would do well to take 2 minutes and change your variable names in this post.
I want to catch exceptions in javascript if an insertion query is not done.
I have written the code below:
var adoConn = new ActiveXObject("ADODB.Connection");
var adoRS = new ActiveXObject("ADODB.Recordset");
var rec = new ActiveXObject("ADODB.Record");
adoConn.Open="DRIVER={MySQL ODBC 3.51 Driver};SERVER=172.25.37.145;" + "DATABASE=confluence;UID=root;PASSWORD=somePassword;OPTION=3";
//Connectionstring
alert('Database Connected');
adoConn.Execute("insert into `session` (SessionId,Timestamp) values ('"+SessionId+"','"+SessionCurrenttime+"')");
If I get the same session id then the query was not executed as it is the primary key in the database.
To be complete, here's the full structure
try {
// your code that can throw exception goes here
} catch(e) {
//do stuff with the exception
} finally {
//regardless if it worked or not, do stuff here (cleanup?)
}
<script language="JavaScript">
try
{
colours[2] = "red";
}
catch (e)
{
alert("Oops! Something bad just happened. Calling 911...");
}
</script>
(Ripped from http://www.devshed.com/c/a/JavaScript/JavaScript-Exception-Handling/)
try {
// your code that can throw exception goes here
} catch(e) {
//do stuff with the exception
}
FYI - the code you posted looks, well, for want of a better word, ugly! (No offense) Couldn't you use DWR or some other JavaScript framework (depending on your language choice) to hide all the DB connection stuff at the back end and just have the javascript calling the back end code and doing something with the response?
try {
adoConn.Execute("insert into session (SessionId,Timestamp) values ('"
+ SessionId + "','"
+ SessionCurrenttime + "')");
} catch(e) {
/*use error object to inspect the error: e.g. return e.message */
}