流应用程序/ json POST请求

时间:2016-04-08 23:02:10

标签: node.js http post fs

我有工作代码来缓冲.json文件,然后将该数据发送到服务器。

  fs.readFile(filePath, 'utf-8', function (err, buf) {

        if(err){
            reject(err);
        }
        else{
            const req = http.request({
                method: 'POST',
                host: 'localhost',
                path: '/event',
                port: '4031',
                headers: {
                    'Content-Type': 'application/json',
                    'Content-Length': buf.length
                }
            });


            req.on('error', reject);

            var data = '';

            req.on('response', function (res) {

                res.setEncoding('utf8');

                res.on('data', function ($data) {
                    data += $data
                });

                res.on('end', function () {

                    data = JSON.parse(data);
                    console.log('data from SC:', data);

                    //call fn on data and if it passes we are good
                    resolve();
                });
            });

            // write data to request body
            req.write(buf);
            req.end();
        }


    });

我想要做的是避免缓冲它,只需使用fs.createReadStream,就像这样:

  fs.createReadStream(filePath, 'utf-8', function (err, strm) {

    if(err){
        reject(err);
    }
    else{
        const req = http.request({
            method: 'POST',
            host: 'localhost',
            path: '/event',
            port: '4031',
            headers: {
                'Content-Type': 'application/json',
                // 'Content-Length': buf.length
            }
        });


        req.on('error', reject);

        var data = '';

        req.on('response', function (res) {

            res.setEncoding('utf8');

            res.on('data', function ($data) {
                data += $data
            });

            res.on('end', function () {

                data = JSON.parse(data);
                console.log('data from SC:', data);

                //call fn on data and if it passes we are good
                resolve();
            });
        });

        // write data to request body
        req.write(strm);
        req.end();
    }


});

但这不太有效?有可能这样做吗?

1 个答案:

答案 0 :(得分:0)

这似乎有效,但不确定它是否100%正确

const strm = fs.createReadStream(filePath);


const req = http.request({
    method: 'POST',
    host: 'localhost',
    path: '/event',
    port: '4031',
    headers: {
        'Content-Type': 'application/json',
    }
});


req.on('error', reject);

var data = '';

req.on('response', function (res) {

    res.setEncoding('utf8');

    res.on('data', function ($data) {
        data += $data
    });

    res.on('end', function () {

        data = JSON.parse(data);
        resolve();
    });
});

// write data to request body
strm.pipe(req);