通过readStream将数组的值与javascript文件一起发送到客户端?

时间:2015-12-01 12:37:38

标签: javascript node.js node-mysql cfreadstream

我有一个node.js服务器使用node-mysql提取数据并将其保存到名为FRUITS的数组中。

我需要使用'readStream'发送给客户端的javascript文件传输此数组的值(FRUITS)。

关于如何做到这一点的任何想法?代码

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 个答案:

答案 0 :(得分:0)

这会将fruits数组作为JSON附加到js文件并将其流式传输:

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

通过这种方式,您可以将此var FRUITS = ["apple","banana"];附加到fruits.js,这样如果您使用FRUITS作为脚本,则可以使用fruits.js作为变量。