Sending value of an array to client alongside javascript file via readStream?

530 Views Asked by At

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
    })
}
1

There are 1 best solutions below

6
On

This will append the fruits array as JSON to the js file and stream it:

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);
    }

    var fileVar = 'var FRUITS = '+JSON.stringify(FRUITS)+';';

    fs.appendFile('./fruits.js', fileVar, function(err) {
        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);
        })
    });
 });

In this way you will append this var FRUITS = ["apple","banana"]; to the fruits.js so you can use FRUITS as variable if you use fruits.js as script.