Node.js : Write new data to an existing json file - json

I'm trying to add data to an existing json file (codes below). When I access the locahost, the new piece of data shows up, however, when I check the data (users.json), the new piece of data (i.e. user4) isn't there.
Does anyone know what's wrong with the code? Thank you!
var express = require('express');
var app = express();
var fs = require("fs");
var user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
}
app.get('/addUser', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
res.end( JSON.stringify(data));
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
EDIT:
I added fs.writeFile(...) (codes below). After running the code, the only content of the uers.json file is:utf8
var express = require('express');
var app = express();
var fs = require("fs");
var user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
}
app.get('/addUser', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
// res.end( JSON.stringify(data));
data = JSON.stringify(data);
fs.writeFile(__dirname+"/"+"users.json", "utf8", function(err,data){
if (err){
console.log(err);
};
res.end(data);
});
});
})

To write to a file you should use fs.writeFile.
fs.writeFile(__dirname + "/" + "users.json", user["user4"], 'utf8', function()
{
// do anything here you want to do after writing the data to the file
});

I have passed data to writeFile so that it may write the information in data variable to JSON
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
data = JSON.stringify(data);
fs.writeFile(__dirname + "/" + "users.json", data , 'utf8', function(err,data) {
if (err){
console.log(err);
};
res.end(data);
});
});

Related

Generating a PDF file using data from MySQL database in Node js

I am trying to generate a PDF file using the data stored in the Mysql database using Node js, Pdfkit and pdfkit-table. I need to print the records in database to a table in the PDF document.
The below code generates an empty PDF file. Please help me to solve the problem of why it does not generate a PDF file with data.
This is index.js file.
var express = require('express');
var router = express.Router();
var PDFDocument = require('pdfkit');
var orm = require('orm');
var PDFDoc = require("pdfkit-table");
router.use(orm.express("mysql://root:#localhost:/kirula_fashion", {
define: function (db, models, next) {
models.news = db.define("ledger", {
id : String,
date : String,
description : String,
debit : String,
credit : String,
});
next();
}
}));
router.get('/', function(req, res, next) {
var result = req.models.news.find({
}, function(error, news){
if(error) throw error;
res.render('index', { news:news, title: 'Generate PDF using NodeJS'
});
});
});
router.get('/pdf', function(req, res, next) {
var id = req.query.id;
const doc = new PDFDocument();
const docTable = new PDFDoc();
var result = req.models.news.find({id: id}, function(error, newspost){
if(error) throw error;
else{
if(newspost.length>0){
for(var i=0; i<newspost.length;i++){
var date = newspost[0]['date'];
var description = newspost[0]['description'];
var debit = newspost[0]['debit'];
var credit = newspost[0]['credit'];
var table = {
title: "Ledger records",
subtitle: "May - 2020",
headers: [
{ "label":"Date", "property":"date", "width":100 },
{ "label":"Description", "property":"description", "width":100 },
{ "label":"Debit", "property":"debit", "width":100 },
{ "label":"Credit", "property":"credit", "width":100 }
],
datas:
[
{ "date":date, "description":description, "debit":debit, "credit":credit},
{
"renderer": "function(value, i, irow){ return value + `(${(1+irow)})`; }"
}
],
};
docTable.table( table, {
width: 300,
});
}
}
}
var title = "Ledger for May 2020";
var filename = encodeURIComponent(title) + '.pdf';
res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"');
res.setHeader('Content-type', 'application/pdf');
doc.pipe(res);
doc.end();
});
});
module.exports = router;
I encounter the same issue with datas options, however with rows options pdfkit-table work nicely, maybe mapping from [{..},{...}] to [[..],[...]] then use rows option

When I upload image through multer , I got image undefined error

I am using it with node and mysql with angular 5.
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './assets/images/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
const fileFilter = (req, file, cb)=>{
if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
cb(null, true);
}
else{
cb(null, false);
}
};
upload = multer({
storage: storage,
limits:{
filesize : 1024 * 1024 * 5
},
fileFilter : fileFilter
});
const app = express();
//DATABASE CONNECTION
const connection = mysql.createConnection({
host: 'localhost',
user:'root',
password: 'root',
database: 'inpblog',
port: 8889
});
// ALLOW CROSS ORIGIN
const corsOptions = {
origin: 'http://localhost:4200',
origin1: 'http://localhost:4202',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));
app.use('./assets/images', express.static(path.join(__dirname, 'dist', 'upload')));
const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
connection.connect(function(error){
if(!!error){
console.log("error - db not connected");
}
else{
console.log("connected");
}
});
Here i define the code to upload a image in mysql database. through postman its upload a image in destination folder with multer middleware but when i upload a image through ng form its showing error in console."image undefined" and submit the "c:/fakepath/image.jgg" in mysql.
Here is the API to insert the post
app.post('/insertPost', upload.single('txt_blog_image'), jsonParser, (req, res) => {
console.log("image: ", req.file); // working fine only with postman
//console.log("rBody: ", req.body.txt_blog_image); // working fine only with Angular
let blogFields = {
post_author : req.body.txt_blog_author,
post_image : req.body.txt_blog_image
};
let sql = 'INSERT INTO insdb SET ?';
let query = connection.query(sql, blogFields, (err,result)=> {
res.send('New Post added...');
});
});
// Get All Post
app.get('/getallposts', (req, res) => {
let sql = 'SELECT * FROM insdb';
let query = connection.query(sql, (err, results) => {
if(err) throw err;
console.log(results);
res.send(results);
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.listen(4202);
Try this way.
var path = require('path');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './assets/images/')
},
filename: function(req, file, callback) {
console.log(file)
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
In your api :
app.post('/getallposts',upload.single("image") , function(req, res) {
let sql = 'SELECT * FROM insdb';
let query = connection.query(sql, (err, results) => {
if(err) throw err;
console.log(results);
res.send(results);
});
})
From Angular side :
let form = new FormData();
form.append('image' , file);
Then console in server side , req.files to check file is coming or not ?
For more information and example please see this link

Store JSON data in MySQL table

I have a problem with storing JSON data in MySQL table using NodeJS.
JSON data looks like this:
{
"header":
{
"file1":0,
"file2":1,
"subfiles":{
"subfile1":"true",
"subfile2":"true",
}
},
"response":
{
"number":678,
"start":0,
"docs":[
{
"id":"d3f3d",
"code":"l876s",
"country_name":"United States",
"city":"LA"
},
{
"id":"d2f2d",
"code":"2343g",
"country_name":"UK",
"city":"London"
}
]
}
}
and I want to store only fields in docs array (or response object).
I'm trying to get data and store in mysql in this way:
var express = require('express');
var mysql = require('mysql');
var request = require("request");
var app = express();
app.use('/', express.static('../client/app'));
app.use('/bower_components', express.static('../client/bower_components/'));
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
app.jsonParser = bodyParser.json();
app.urlencodedParser = bodyParser.urlencoded({ extended: true });
//mysql connection setup
var connection = mysql.createConnection({
host : "localhost",
port: "3306",
user : "root",
password : "root",
database : "db",
multipleStatements: true
});
request('http://url.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(body) //
}
var data = body.toString();
console.log(string);
var query = connection.query('INSERT INTO table SET ?', data, function(err, result) {
// Finish
});
console.log(query.sql);
});
server.listen(3000, function () {
'use strict';
});
In log I got
INSERT INTO table SET '{\n \"header\":{\n \"file1\":0,\n \"file2\":1,\n \"subfiles\":{\n \"subfile1\":\"true\",\n \"subfile2\":\"true\"}},\n \"response\":{\"number\":678,\"start\":0,\"docs\":[\n {\n \"id\":\"d3f3d\",\n \"code\":\"l876s\",\n....
output message, but I don't have data in MySQL table.
Do I need to specify every column in query?
at your //Finish comment you should have added some console.log(err) to see why there was no data inserted.
Here the solution:
var data = JSON.parse(body);
var responseJson = JSON.stringify(data.response);
var query = connection.query('INSERT INTO table SET column=?', [responseJson], function(err, result) {
if(err) throw err;
console.log('data inserted');
});

Data not getting saved in the MongoDB from node.js

I want to create the rest api using node.js and mongodb
I am entering all the details and trying it to store it in the mongodb database.
// call the packages we need
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var morgan = require('morgan');
// configure app
app.use(morgan('dev')); // log requests to the console
// configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
var mongoose = require('mongoose');
// mongoose.connect('mongodb://node:node#novus.modulusmongo.net:27017/Iganiq8o'); // connect to our database
mongoose.connect('mongodb://localhost:27017');
var Bear = require('./app/models/bear');
// create our router
var router = express.Router();
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next();
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
// create a bear (accessed at POST http://localhost:8080/bears)
.post(function(req, res) {
var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)
bear.email= req.body.email; // set the bears email(comes from the request)
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
})
// get all the bears (accessed at GET http://localhost:8080/api/bears)
.get(function(req, res) {
Bear.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
// on routes that end in /bears/:bear_id
// ----------------------------------------------------
router.route('/bears/:bear_id')
// get the bear with that id
.get(function(req, res) {
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
res.json(bear);
});
})
// update the bear with this id
.put(function(req, res) {
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
bear.name = req.body.name;
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear updated!' });
});
});
})
// delete the bear with this id
.delete(function(req, res) {
Bear.remove({
_id: req.params.bear_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
// REGISTER OUR ROUTES -------------------------------
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
The Model is given below:-
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String,
email: String
});
module.exports = mongoose.model('Bear', BearSchema);
I am trying it to save the name and the email in the mongodb database but only _id is created instead of name, email.
Here is the result:-
[
{
"_id": "567f1f92db24304013000001",
"__v": 0
},
{
"_id": "567f2765db24304013000002",
"__v": 0
}
]
Can anybody tell me why the data are not getting saved in the database.
Please kindly help.
Thanks in Advance.
I think your POST request is not good, so I made this simple script to check it out:
var XHR = (function() {
var _xhr = (function() {
try {
return new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
} catch (e) {}
})();
return function(method, url, params, callback) {
_xhr.onreadystatechange = function() {
if (_xhr.readyState == 4) {
var _response;
try {
_response = JSON.parse(_xhr.response);
} catch (e) {
_response = _xhr.responseText;
}
if (_xhr.status != 200) {
// catch an error
console.error('error', response);
} else {
if (callback) {
callback(_response);
} else {
// deal with it
}
}
}
}
if (!params) {
params = JSON.stringify({});
} else {
params = JSON.stringify(params);
}
_xhr.open(method, url, true);
// just json in this case
_xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
_xhr.send(params);
};
})();
fire it up in browser's console, like this
XHR('POST','api/bears', { name:'yogi', email:'yogi#bears.com'}, function(){ console.log(arguments) });
and your record will be saved.
{ "_id" : ObjectId("567e875d068748ee5effb6e0"), "email" : "yogi#bears.com" "name" : "yogi", "__v" : 0 }
Long story short - your code is okay, your POST is not.

Node js call function, that access mysql database and returns json result, multiple times

I'm new to Node.js. I have a function 'getFromDb' that accesses a mysql database and returns a json file with some data. What if I have an array of query data and I want to call the same function through a for loop to get a json file for each element of the array?
var http = require('http');
http.createServer(function(req, res) {
console.log('Receving request...');
var callback = function(err, result) {
res.setHeader('Content-disposition', 'attachment; filename=' + queryData+ '.json');
res.writeHead(200, {
'Content-Type' : 'x-application/json'
});
console.log('json:', result);
res.end(result);
};
getFromDb(callback, queryData);}
).listen(9999);
function getFromDb(callback, queryData){
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'xxxx',
password : 'xxxx',
database : 'xxxx',
port: 3306
});
connection.connect();
var json = '';
var data = queryData + '%';
var query = 'SELECT * FROM TABLE WHERE POSTCODE LIKE "' + data + '"';
connection.query(query, function(err, results, fields) {
if (err)
return callback(err, null);
console.log('The query-result is: ', results);
// wrap result-set as json
json = JSON.stringify(results);
/***************
* Correction 2: Nest the callback correctly!
***************/
connection.end();
console.log('JSON-result:', json);
callback(null, json);
});
}
You could use the async library for node for this. That library has many functions that make asynchronous programming in NodeJS much easier. The "each" or "eachSeries" functions would work. "each" would make all the calls to mysql at once time, while "eachSeries" would wait for the previous call to finish. You could use that inside your getFromDB method for your array.
See:
https://github.com/caolan/async#each
var http = require('http'),
async = require('async');
http.createServer(function(req, res) {
console.log('Receving request...');
var callback = function(err, result) {
res.setHeader('Content-disposition', 'attachment; filename=' + queryData+ '.json');
res.writeHead(200, {
'Content-Type' : 'x-application/json'
});
console.log('json:', result);
res.end(result);
};
getFromDb(callback, queryData);}
).listen(9999);
function getFromDb(callback, queryData){
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'xxxx',
password : 'xxxx',
database : 'xxxx',
port: 3306
});
connection.connect();
var arrayOfQueryData = ["query1", "query2", "query3", "query4", "query5"];
var jsonResults = [];
async.each(arrayOfQueryData, function (queryData, cb) {
var data = queryData + '%';
var query = 'SELECT * FROM TABLE WHERE POSTCODE LIKE "' + data + '"';
connection.query(query, function(err, results, fields) {
if (err)
return cb(err);
console.log('The query-result is: ', results);
// wrap result-set as json
var json = JSON.stringify(results);
console.log('JSON-result:', json);
jsonResults.push(json);
cb();
});
}, function (err) {
connection.end();
// callbacks from getFromDb
if (err) {
callback(err);
}
else {
callback(null,jsonResults);
}
});
}
use async module. it is the best one. If u dont want to add new module try following;
var count = 0;
array.forEach(function(element) { //array of the data that is to be used to call mysql
++count; //increase counter for each service call
async.db.call(element, callback); //the async task
}
var data = [];
function callback(err, resp) {
--count;//subtract for each completion
data.push(resp)
if(count == 0) { //return data when all is complete
return data;
}
}
I would recommend the async module though. it is very good practice and useful.