Skip to content

Instantly share code, notes, and snippets.

@karmadude
Created December 8, 2011 03:34
Show Gist options
  • Save karmadude/1445992 to your computer and use it in GitHub Desktop.
Save karmadude/1445992 to your computer and use it in GitHub Desktop.
Using Node to export MySQL query results to a file as JSON
// https://github.com/felixge/node-mysql
// npm install mysql
var mysql = require('mysql');
// http://nodejs.org/docs/v0.6.5/api/fs.html#fs.writeFile
var fs = require('fs');
var client = mysql.createClient({
user: 'root',
password: 'mysqlpassword'
});
client.query('select * from db.table;', function(err, results, fields) {
if(err) throw err;
fs.writeFile('table.json', JSON.stringify(results), function (err) {
if (err) throw err;
console.log('Saved!');
});
client.end();
});
@deepbratt
Copy link

var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "staging"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "SELECT * FROM products";
  con.query(sql, function (err, result) {
    if (err) throw err;
    res.end(JSON.stringify(result));
  });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment