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



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

我需要使用"readStream"将此数组(FRUITS)的值与发送到客户端的javascript文件一起传输。。

有什么想法吗?下方的代码

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

这将把水果数组作为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.js作为脚本,您就可以使用FRUITS作为变量。

相关内容

  • 没有找到相关文章

最新更新