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...')
}
})
}
}
)
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.
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);
.
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);
});
i want to run a script that will create a directory and within a file and subdirectory, something like this
main-folder
> sub-folder
> file
so far i haven't had any luck, my thought is trying to writeFile within the mkDir function
const fileGenerator = (fileName, fileContent) => {
fs.writeFile(fileName, fileContent, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
}
fs.mkdir('main-folder', err => {
if (err) {
console.log(err);
} else {
fileGenerator('index.html', 'hello');
console.log('Directory Created');
fs.mkdir('sub-folder', err => {
if (err) {
console.log(err);
} else {
console.log('Directory Created');
}
})
}
})
The code is 'working as inteded'. The place where're you creating your subfolder and file is just the callback. The mkdir function from the Node Filesystem still needs the full path. It doesn't know that its under "main-folder".
See the edited code:
const fs = require('fs');
const fileGenerator = (fileName, fileContent) => {
fs.writeFile(fileName, fileContent, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
}
fs.mkdir('main-folder', err => {
if (err) {
console.log(err);
} else {
fileGenerator('main-folder/index.html', 'hello');
console.log('Directory Created');
fs.mkdir('main-folder/sub-folder', err => {
if (err) {
console.log(err);
} else {
console.log('Directory Created');
}
})
}
})
Your code created the main-folder, sub-folder and index.html, just all relative to js file.
I'm trying to implement a promise-based approach to accessing a PostgreSQL database. This is the original code:
// ./sql/config/pgQuery.js
module.exports = (text, values, cb) => {
pool.connect((err, client, done) => {
if (err) return cb(err);
client.query(text, values, (err, result) => {
done();
if (err) return cb(err);
return cb(null, result.rows, result);
});
});
};
// ./routes/pg.js
router.route('/')
.get((req, res) => {
const values = [];
query('DROP TABLE IF EXISTS users', values, (err, rows, all) => {
if (err) throw err;
console.log('DROP TABLE IF EXISTS users');
res.status(204).end();
});
const text = 'CREATE TABLE IF NOT EXISTS users (date timestamptz)';
query(text, values, (err, rows, all) => {
if (err) throw err;
console.log('CREATE TABLE IF NOT EXISTS users');
res.status(204).end();
});
});
This is what I come up with so far, but it doesn't work:
// ./sql/config/pgQuery.js
function promisePool() {
return new Promise((resolve, reject) => {
return (text, values, cb) => {
pool.connect((err, client, done) => {
if (err) { cb(err); return; }
client.query(text, values, (err, result) => {
done();
if (err) { reject(err); return; }
return resolve(cb(null, result.rows, result));
});
});
};
});
}
module.exports = promisePool;
// ./routes/pg.js
router.route('/')
.get((req, res) => {
const values = [];
query()
.then('DROP TABLE IF EXISTS users', values, (err, rows, all) => {
if (err) throw err;
console.log('DROP TABLE IF EXISTS users');
res.status(204).end();
})
.then('CREATE TABLE IF NOT EXISTS users (date timestamptz)', values, (err, rows, all) => {
if (err) throw err;
console.log('CREATE TABLE IF NOT EXISTS users');
res.status(204).end();
});
});
Thank You for your help!