I have:
var url = "mongodb+srv://exampleuser:53pr1WkCUkkOon0q#cluster0-zfo5z.mongodb.net/test?retryWrites=true&w=majority&useUnifiedTopology=true";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("rw_bewerbung");
var query = { mc_uuid: uuid };
dbo.collection("user_name_history").find(query).toArray(function(err, result) {
if (err) throw(err);
nameHistory = result[0].name_history;
db.close();
});
});
And I want to get the variable nameHistory...how can I do this?
You can do this by converting your code into a promise:
const bewerbung = async (url) => new Promise((resolve, rejected) => {
MongoClient.connect(url, function(err, db) {
if (err) {
rejected(err);
} else {
const dbo = db.db("rw_bewerbung");
const query = {mc_uuid: uuid};
dbo
.collection("user_name_history")
.find(query)
.toArray(function (err, result) {
if (err) {
rejected(err);
} else {
db.close();
resolve(result[0]);
}
});
}
});
}).catch(console.error);
const url = "todo...";
const res = await bewerbung(url);
const nameHistory = res.name_history;
console.info('nameHistory', nameHistory);
.
Related
function Getir() {
var options =
{
host: 'example',
port: 443,
path: '/myUrl'
};
get(options, function (http_res) {
var data = "";
http_res.on("data", function (chunk) {
data += chunk;
});
http_res.on("end", function () {
writeFile('NewHtml.txt', `${data}`, 'utf8', (err) => {
if (err) console.log(err);
});
});
});
}
function DegistirDuzenle() {
if (existsSync("./DatabaseHtml.txt")) {
var DataBaseHtml = readFileSync("./DatabaseHtml.txt", 'utf-8', (err) => { if (err) console.log(err) });
var MyHtml = readFileSync("./NewHtml.txt", 'utf-8', (err) => {if (err) console.log(err) });
if (MyHtml == DataBaseHtml) {
unlink("./NewHtml.txt", (err)=>{ if(err) console.log(err)});
console.log("değişiklik yapılmadı");
} else {
//notification
console.log("değişiklik yapıldı");
//Change
unlink('./DatabaseHtml.txt', (err) => { if(err) console.log(err); });
writeFile('./DatabaseHtml.txt', `${MyHtml}`, 'utf-8', (err) => { if(err) console.log(err); });
unlink('./NewHtml.txt', (err) => { if(err) console.log(err); });
}
}
else {
writeFile('DatabaseHtml.txt', `NewDataBaseHtml`, 'utf8', (err) => {
if (err) console.log(err);
});
}
}
async function Mysystem() {
let mypromis = new Promise((resolve, reject)=>{
resolve(Getir());
});
await mypromis.then(DegistirDuzenle());
}
Mysystem();
I want to create a txt file, read it and delete it later. I have 2 function 1.(Getir()) Create txt, 2.(DegistirDuzenle()) read txt and delete but 2. function starts working first and I getting error. "Error: ENOENT: no such file or directory, open './NewHtml.txt'"
async function Mysystem() {
let mypromis = new Promise((resolve, reject)=>{
resolve(Getir());
});
await mypromis()
await DegistirDuzenle()
}
Mysystem()
You should use
async function Mysystem() {
await Getir();
await DegistirDuzenle();
}
or
function Mysystem() {
return Getir().then(DegistirDuzenle);
}
but not a mix of them. Also notice that when passing the DegistirDuzenle function to .then() as a callback, it shouldn't be invoked (passing the result of a call, not passing the function). Alternatively, you could write .then((getirResult) => DegistirDuzenle()).
Also, for this to work, you'll need to properly promisify the code in Getir and DegistirDuzenle.
So I come to this, I want to write into a DB and do other operations to work with my program logic, this is the guide that I'm following Node.js Class Creation:
//## This is my mysql_test.js file
function MySQL(){
var mysql = require('mysql');
var con = mysql.createConnection({
//data omitted
});
function AppendRecordset (req, res){
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(req, function (err, res) {
if (err) throw err;
console.log("1 record inserted");
});
});
}
function UpdateRecordset (req, res) {
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
}
function DeleteRecordset (req, res){
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});
}
function GetRecordset (req, res) {
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res, fields) {
if (err) throw err;
console.log(result);
});
});
}
}
I then have in a separate file(s) my app logic, and want to use what of the above as an object/class so I wrote this accordingly to that guide:
//##this is inside my main app file
//declare the sql processor
require('./mysql_test.js');
var DB = MySQL();
DB.AppendRecordset(sql_string, res); //sql_string contains a valid SQL statement
But when I try to acces it using `` I get this error message: ReferenceError: MySQL is not defined what am I doing wrong?
I think these functions handle your routes, so I didn't change them. Because I don't know how your router is desined.
Create a file dbHangler.js and write this single function:
const mysql = require('mysql');
let con;
exports.execQuery = (query) => {
return new Promise((resolve, reject) => {
if(!con) {
con = mysql.createConnection({
//data omitted
});
}
con.connect(function(err) {
if(err) {
reject(err);
}
else {
console.log("Connected!");
con.query(query, function (err, res) {
if (err) {
reject(err);
}
else {
resolve(res);
}
});
}
});
});
};
In your dedicated.js file, now you can write:
const dbObject = require('path/to/dbHandler');
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log(result.affectedRows + " record(s) updated");
})
.catch(error => {
// handle error
});
}
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log("Number of records deleted: " + result.affectedRows);
})
.catch(error => {
// handle error
});
}
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log(result);
})
.catch(error => {
// handle error
});
}
UPDATE
I hope this one helps you.
DbHandler.js
const mysql = require('mysql');
class DbHandler {
constructor(config) {
let self = this;
self.dbConfig = config;
self.connection = mysql.createConnection({
//data omitted
});
}
queryExecuter(query) {
let self = this;
return new Promise((resolve, reject) => {
self.connection.connect(function (err) {
if (err) {
reject(err);
}
else {
console.log("Connected!");
self.connection.query(query, function (err, res) {
if (err) {
reject(err);
}
else {
resolve(res);
}
});
}
});
});
}
AppendRecordset(query) {
let self = this;
return self.queryExecuter(query)
.then(result => {
console.log("1 record inserted");
return result;
})
.catch(error => {
// handle error
throw error;
});
}
UpdateRecordset(query) {
let self = this;
return self.queryExecuter(query)
.then(result => {
console.log(result.affectedRows + " record(s) updated");
return result;
})
.catch(error => {
// handle error
throw error;
});
}
// and other functions
}
module.exports = DbHandler;
And use it like below:
let DB = require('/path/to/DbHandler');
let myDb = new DB(/* db config */);
db.UpdateRecordset('your query')
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
Here is my code:
const AWS = require('aws-sdk');
const { Client } = require('pg');
function main() {
AWS.config.update({region:'eu-west-2'});
let db_user = {
Name: "postgres_db_user",
WithDecryption: false
};
let db_host = {
Name: "postgres_db_host",
WithDecryption: false
};
let db_database = {
Name: "postgres_db_name",
WithDecryption: false
};
let db_password = {
Name: "postgres_db_password",
WithDecryption: true
};
let db_port = {
Name: "postgres_db_port",
WithDecryption: false
};
let database_user_name;
let database_host;
let database_name;
let database_port;
let database_password;
let ssm = new AWS.SSM();
ssm.getParameter(db_user, function (err, data) {
if (err) {
console.log(err, err.stack);
} else {
database_user_name = data;
}
});
ssm.getParameter(db_host, function (err, data) {
if (err) {
console.log(err, err.stack);
} else {
database_host = data;
}
});
ssm.getParameter(db_database, function (err, data) {
if (err) {
console.log(err, err.stack);
} else {
database_name = data;
}
});
ssm.getParameter(db_password, function (err, data) {
if (err) {
console.log(err, err.stack);
} else {
database_password = data;
}
});
ssm.getParameter(db_port, function (err, data) {
if (err) {
console.log(err, err.stack);
} else {
database_port = data;
}
});
console.log(database_user_name);
console.log(database_host);
console.log(database_name);
console.log(database_password);
console.log(database_port);
let client = new Client({
user: database_user_name,
host: database_host,
database: database_name,
password: database_password,
port: database_port,
});
}
main();
The problem is that when I print the variables they are undefined, and I have no idea why. The SSM getParameter function is working because if I use the debugger, I see the values, but it doesn't seem to save the data variable in the variables for some strange reason.
If someone could help me as to why this code is printing undefined for the variables I would appreciate it.
I was drafting my answer when John commented :).
getParameter is async function and it's being executed while you are initializing the client with properties.
Here is some sample way of coding initialization.(not perfect but you can get the idea).
var AWS = require('aws-sdk');
AWS.config.update({ region: 'us-east-1' });
var ssm = new AWS.SSM();
function getParameter(param) {
return new Promise(function (success, reject) {
ssm.getParameter(param, function (err, data) {
if (err) {
reject(err);
} else {
success(data);
}
});
});
};
function main() {
let db_user = {
Name: "postgres_db_user",
WithDecryption: false
};
let database_user_name;
var promises = [];
promises.push(getParameter(db_user));
Promise.all(promises)
.then(function (result) {
database_user_name = result[0].Parameter.Value;
console.log(database_user_name);
let client = new Client({
user: database_user_name
//rest of the properties
});
//rest of the main() function code
})
.catch(function (err) {
console.log(err);
});
}
main();
Reference -
https://stackoverflow.com/a/44868681/5030709
I have three different sample.xml files which I have to convert into json output. I am trying to append all of their output into one json file. here is my code
const fs = require('fs');
const xml2js = require('xml2js');
parser = new xml2js.Parser({
explicitArray: true
})
fs.readFile('sample.xml', (err, data) => {
parser.parseString(data, (err, result) => {
let output = JSON.stringify(result.planes.plane);
fs.writeFile('output.json', output, 'utf8', (err) => {
if (err) {
throw err;
} else {
console.log('file created..')
}
})
});
});
now I know the function fs.appendfile() but I am not sure how do I do it? I have two more files named: sample2.xml and sample3.xml
this is what I have tried but the problem it is overwriting not appending.
const fs = require('fs');
const xml2js = require('xml2js');
const async = require('async');
parser = new xml2js.Parser({
explicitArray: true
})
let files = ['sample.xml', 'sample2.xml'];
async.map(files, fs.readFile, (err, files) => {
if (err) {
throw err;
} else {
files.forEach((file) => {
parser.parseString(file, (err, result) => {
let output = JSON.stringify(result.planes.plane);
fs.appendFile('output.json', output, 'utf8', (err) => {
if (err) {
throw err;
} else {
console.log('file created..')
}
})
});
})
}
})
You need to read each xml file, get the json-data from it, and then write it to the final file:
async.map(
files,
(file, cb) => {
fs.readFile(file, (err, data) => {
if (err) {
cb(err)
} else {
parser.parseString(data, (err, result) => {
cb(err, result.planes.plane)
})
}
})
},
function (err, results) {
if (err) {
throw err
} else {
let output = JSON.stringify(results)
fs.writeFile('output.json', output, 'utf8', (err) => {
if (err) {
throw err
} else {
console.log('file created...')
}
})
}
}
)
The following code is the same code used in the node-oracledb GitHub examples, called select1.js. I just modified it a little bit.
module.exports = function() {
var oracledb = require('oracledb');
var dbConfig = require('./dbconfig.js');
this.queryDB = function (query) {
oracledb.getConnection({
user : dbConfig.user,
password : dbConfig.password,
connectString : dbConfig.connectString
}, function(err, connection) {
if (err) {
console.error(err.message);
return;
}
connection.execute(query, function(err, result) {
if (err) {
console.error(err.message);
doRelease(connection);
return;
}
console.log(result.metaData);
console.log(result.rows);
doRelease(connection);
return result.rows
});
});
function doRelease(connection) {
connection.release(function(err) {
if (err) {
console.error(err.message);
}
});
}
}
}
This can be used as follow:
require('./dbquery.js')();
console.log(queryDB("SELECT * FROM users"));
I expected to see the same 2D matrix (representing the table) as on line "console.log(result.rows);". But the "console.log(queryDB("SELECT * FROM users"));" returns "undefined".
How can I return a value that I get in the callback function?
I tried to add a variable X at the beginning, like this:
module.exports = function() {
var oracledb = require('oracledb');
var dbConfig = require('./dbconfig.js');
this.queryDB = function (query) {
var X;
oracledb.getConnection({
user : dbConfig.user,
password : dbConfig.password,
connectString : dbConfig.connectString
}, function(err, connection) {
if (err) {
console.error(err.message);
return;
}
connection.execute(query, function(err, result) {
if (err) {
console.error(err.message);
doRelease(connection);
return;
}
console.log(result.metaData);
console.log(result.rows);
doRelease(connection);
X = result.rows
});
});
function doRelease(connection) {
connection.release(function(err) {
if (err) {
console.error(err.message);
}
});
}
return X;
}
}
But this is still undefined. How can I achieve this ?
It's running in async nature. You can resolve it with callback or promises. You can't get value like this.
pass the callback and return with callback
module.exports = function(callback) {//pass callback function and return with this
var oracledb = require('oracledb');
var dbConfig = require('./dbconfig.js');
this.queryDB = function(query,callback) {
oracledb.getConnection({
user: dbConfig.user,
password: dbConfig.password,
connectString: dbConfig.connectString
}, function(err, connection) {
if (err) {
console.error(err.message);
return callback(err);
}
connection.execute(query, function(err, result) {
if (err) {
console.error(err.message);
doRelease(connection);
return;
}
console.log(result.metaData);
console.log(result.rows);
doRelease(connection);
return callback(null, result.rows)
});
});
function doRelease(connection) {
connection.release(function(err) {
if (err) {
console.error(err.message);
return callback(err);
}
});
}
};
};