I have a node.js server pulling data using node-mysql and saving it into an array called FRUITS.
I need to transfer the value of this array (FRUITS) with the javascript file that i send to the client using 'readStream'..
Any ideas on how to do this? Code below
nodeController.js
function sendJSfile(req, res) {
seed_id = "valid_fruits"
var mysql = require('mysql');
var end;
var connection = mysql.createConnection({
host: 'myhost',
user: 'username',
password: 'password',
database: 'databasename'
});
connection.connect()
connection.query({
sql: 'SELECT fruit_type FROM fruit_table WHERE seed_id = ? LIMIT 0, 10',
timeout: 4000,
values: [seedid]
}, function (err, result, fields) {
var FRUITS = [];
for (var i = 0; i < result.length; i++) {
var obj = result[i]
FRUITS.push(obj.fruit_type)
}
})
res.writeHead(200, { "Content-Type": "text/javascript" });
var readStream = fs.createReadStream("./fruits.js")
readStream.on('open', function () {
readStream.pipe(res);
});
readStream.on('error', function (err) {
res.end(err);
})
Client.js
// I use a post request because I need to send data to the server then receive the javascript file back via readStream
request("myserver", "post", { apples })
.done(function (res) {
})
})
function request(url, method, data) {
return $.ajax({
url: url,
method: method,
data: data
})
}
This will append the fruits array as JSON to the js file and stream it:
In this way you will append this
var FRUITS = ["apple","banana"];
to thefruits.js
so you can useFRUITS
as variable if you usefruits.js
as script.