var ComfyJS = require("comfy.js");
var fs = require('fs');
const dataBuffer = fs.readFileSync('database.json');
const dataJSON = dataBuffer.toString();
const scoreBoard = JSON.parse(dataJSON);
ComfyJS.onChat = (user, message, flags, self, extra) => {
for (let i = 0; i < scoreBoard.length; i++) {
if (scoreBoard[i].name == user) {
console.log('The name already exist');
}
else{
scoreBoard.push({name:user,score:message});
}
}
var data = JSON.stringify(scoreBoard);
fs.writeFile('database.json', data, function (err) {
if (err) {
console.log('There has been an error saving your configuration data.');
console.log(err.message);
return;
}
console.log('Configuration saved successfully.')
});
}
Hi I'm new to code and I'd like to build a twitch bot and I want to save my data on a JSON file. ComfyJS.onchat triggers when somebody types something on chat and I want to take their name and message(score) as value and save it on my database but I need to save them one by one so if the name already exists in JSON file I don't want to add it. How should I fix it?
ComfyJS.onChat = (user, message, flags, self, extra) => {
const exists = scoreBoard.find(fn => fn.name === user)
if (exists) return;
scoreBoard.push({
name: user,
score: message
});
var data = JSON.stringify(scoreBoard);
fs.writeFile('database.json', data, function(err) {
if (err) {
console.log('There has been an error saving your configuration data.');
console.log(err.message);
return;
}
console.log('Configuration saved successfully.')
});
}
Related
Working in a NodeJS that saves data to a SQL Server Database, it must save data from an array of objects but when I run it I get this error, just looked here and documentation but I don't really understand how to fix it, any help is welcomed. This is the error:
PS D:\Users\****\****\****\****\****> node appb.js
Successful connection
events.js:135
throw new ERR_INVALID_ARG_TYPE('listener', 'Function', listener);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type function. Received type string ('row')
And this is my app.js:
Connection:
var Connection = require("tedious").Connection;
var lstValid = [];
var config = {
server: "SERVER",
authentication: {
type: "default",
options: {
userName: "USERNAME",
password: "PASSWORD",
},
},
options: {
encrypt: true,
database: "DATABASE",
instanceName: 'INSTANCENAME'
},
};
var connection = new Connection(config);
connection.on("connect", function (err) {
console.log("Successful connection");
executeStatement1();
});
connection.connect();
and here's where I insert data:
async function calcWeather() {
const info = await fetch("../json/data.json")
.then(function (response) {
return response.json();
});
for (var i in info) {
const _idOficina = info[i][0].IdOficina;
const lat = info[i][0].latjson;
const long = info[i][0].lonjson;
const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
fetch(base)
.then((responses) => {
return responses.json();
})
.then((data) => {
var myObject = {
Id_Oficina: _idOficina,
// Other thins in myObject
};
// validation and saving data to array
if (myObject.Temperatura < 99) {
lstValid.push(myObject);
}
});
}
}
var Request = require("tedious").Request;
var TYPES = require("tedious").TYPES;
function executeStatement1() {
calcWeather();
for (var m = 0; m <= lstValid.length; m++) {
Request = new Request(
"INSERT INTO TB_BI_CSL_RegistroTemperaturaXidOdicina (IdOficina, Humedad, Nubes, Sensacion, Temperatura, Descripcion) VALUES (#IdOficina, #Humedad, #Nubes, #Sensacion, #Temperatura)",
function (err) {
if (err) {
console.log("Couldn't insert data: " + err);
}
}
);
Request.addParameter("IdOficina", TYPES.SmallInt, lstValid[m]);
// Other things inserted
Request.on('requestCompleted',"row", function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log("NULL");
} else {
console.log("Product id of inserted item is " + column.value);
}
});
});
Request.on("requestCompleted", function (rowCount, more) {
connection.close();
});
connection.execSql(Request);
}
}
Seems that there are too many parameters to the request.on(...) method, i.e.:
Request.on('requestCompleted',"row", function (columns)
Should probably be:
Request.on("row", function (columns)
The error says the JavaScript function received arguments that were different than expected:
...ERR_INVALID_ARG_TYPE('listener', 'Function', listener);
If it has never worked, the function was likely mistyped. (If it has worked, it could be bad data coming in)
The next message gives a further information:
"...The "listener" argument must be of type function. Received type string ('row')"
A JavaScript function to do work was expected, but it received a simple string 'row' instead.
events.js:135
This means the error happened in the file 'events.js' on or before line 135.
The TediusJs API Request Docs, provides a reference example:
request.on('row', function (columns) { /* code to process rows */ });
In your example we find:
Request.on('requestCompleted',"row", function (columns) {
Most likely it should be:
Request.on("row", function (columns) {
Although I am not positive which line in your example is line 135.
I have made class model for my view the code below (I'm using nw.js ) :
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database('./../data.sqlite');
class store_model{
constructor() {
this.state = {
_stmt: null
}
}
readAll() {
db.each("SELECT * FROM store ", (res, err) => {
if (err)
console.log(err);
else
console.log(res);
});
}
read(obj) {
db.get("SELECT * FROM store WHERE ID =" + obj.id, (res, err) => {
if (err)
console.log(err);
else if (res !== null)
console.log(res);
else
console.log()
});
}
create(obj) {
try {
db.serialize(() => {
this.state._stmt = db.prepare("INSERT INTO store (name,mail) VALUES (?,?)");
this.state._stmt.run(obj.name , obj.mail);
this.state._stmt.finalize();
})
}
catch (err) {
console.log("There is an error " + err);
}
}
update(obj) {
db.serialize(() => {
this.state._stmt = db.prepare("UPDATE store SET name = COALESCE(?, name) , mail=COALESCE(?,mail) WHERE ID=? ");
console.log(obj.name)
try {
this.state._stmt.run(obj.name, obj.mail, obj.id);
}
catch (err){
console.log(err);
}
this.state._stmt.finalize();
console.log("updated ....");
})
}
delete(obj) {
this.state._stmt = db.prepare("DELETE FROM store WHERE ID=?");
this.state._stmt.run(obj.id);
console.log("supprimer");
}
}
After Made it I want to pass the response of some of my requests to my view in vue.js the problem I meet is that my requests are in asynchronous function so I can't pass directly my response to my view object because of the scope .I would like someone guide me ( A way to pass the responses of my requests) to be able to transmit my responses to my view object
(My view object have attribute to receive data) .
I am working on an application where I can save destinations to my Mongo DB. I would like to throw a custom error when trying to save a destination that already exsist in the DB. Mongoose prevents that from happening but I want clear and userfriendly error handling.
// post a new destination
router.post('/',
(req, res) => {
const newCity = new cityModel(
{
name: req.body.name,
country: req.body.country
}
)
newCity.save()
.then(city => {
res.send(city)
})
.catch(err => {
res.status(500).send('Server error')
})
});
Before saving a new destination, you can check if there is document already using findOne method, and if it exists you can return a custom error.
router.post("/", async (req, res) => {
const { name, country } = req.body;
try {
const existingDestination = await cityModel.findOne({name,country});
if (existingDestination) {
return res.status(400).send("Destionation already exists");
}
let newCity = new cityModel({ name, country });
newCity = await newCity.save();
res.send(city);
} catch (err) {
console.log(err);
res.status(500).send("Server error");
}
});
Note that I guessed the duplication occurs when the same country and name exist. If it is not what you want, you can change the query in findOne.
Since you've created unique index, When you try to write duplicate then the result would be :
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error index: test.collection.$a.b_1 dup key: { : null }"
}
})
Your code :
Constants File :
module.exports = {
DUPLICATE_DESTINATION_MSG: 'Destionation values already exists',
DUPLICATE_DESTINATION_CODE: 4000
}
Code :
//post a new destination
const constants = require('path to constants File');
router.post('/',
(req, res) => {
const newCity = new cityModel(
{
name: req.body.name,
country: req.body.country
}
)
try {
let city = await newCity.save();
res.send(city)
} catch (error) {
if (error.code == 11000) res.status(400).send(`Destination - ${req.body.name} with country ${req.body.country} already exists in system`);
/* In case if your front end reads your error code &
it has it's own set of custom business relates messages then form a response object with code/message & send it.
if (error.code == 11000) {
let respObj = {
code: constants.DUPLICATE_DESTINATION_CODE,
message: constants.DUPLICATE_DESTINATION_MSG
}
res.status(400).send(respObj);
} */
}
res.status(500).send('Server error');
})
I'm using mysql connection pool to create connection. The code looks like the following.
var pool = mysql.createPool(connectionProps);
by accessing pool, I'll get the an Object, even if the connection is not Successful. I checked it with starting and stopping mysql.
What I want is that, I need to check connection is successful or not as follows.
if(pool){ // mysql is started && connected successfully.
console.log('Connection Success');
doSomething();
}else{
console.log('Cant connect to db, Check ur db connection');
}
I want something like this. So how can we do this with the mysql pool Object. Can someone please help me?
Thanks n Regards
Commonly you would do something like select something arbitrary from the db, and catch an error if that failed. Example from the docs.
const pool = mysql.createPool(connectionProps);
pool.query('SELECT 1 + 1 AS solution', (error, results, fields) => {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
var pool = mysql.createPool(config.db);
exports.connection = {
query: function () {
var queryArgs = Array.prototype.slice.call(arguments),
events = [],
eventNameIndex = {};
pool.getConnection(function (err, conn) {
if (err) {
if (eventNameIndex.error) {
eventNameIndex.error();
}
}
if (conn) {
var q = conn.query.apply(conn, queryArgs);
q.on('end', function () {
conn.release();
});
events.forEach(function (args) {
q.on.apply(q, args);
});
}
});
return {
on: function (eventName, callback) {
events.push(Array.prototype.slice.call(arguments));
eventNameIndex[eventName] = callback;
return this;
}
};
}
};
And require to use it like:
db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
.on('result', function (row) {
setData(row);
})
.on('error', function (err) {
callback({error: true, err: err});
});
So i did that kind of code.
var csv = require('csv-stream');
var request = require('request');
var fs = require('fs');
var pg = require('pg');
var conString = "pg://admin:admin#localhost:5432/labels";
// All of these arguments are optional.
var options = {
delimiter : ';', // default is ,
endLine : '\n', // default is \n,
escapeChar : '"', // default is an empty string
enclosedChar : '"', // default is an empty string
}
try {
var csvStream = csv.createStream(options);
fs.createReadStream('personss.csv').pipe(csvStream)
.on('error', function (err) {
console.error(err);
})
.on('data', function (data) {
// outputs an object containing a set of key/value pair representing a line found in the csv file.
console.log(data);
pg.connect(conString, function (err, client, done) {
client.query(
'INSERT into test (firstname, lastname) from',
function (err, result) {
if (err) {
console.log(err);
} else {
console.log('data inserted');
}
});
});
});
} catch (e) {
console(e.message);
};
where i stream the csv file with csv-stream library, how i can insert now that values from variable 'data' to my database? Should i do it by for cycle?
Update
added for cycle to iterate data
pg.connect(conString, function (err, client, done) {
for (var i = 0; data.length; i++) {
client.query(
'INSERT into test (firstname, lastname)',
function (err, result) {
if (err) {
console.log(err);
} else {
console.log('data inserted' + result.data[0]);
}
});
};
});