在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ NodeJS如何發(fā)送buffer類型的數(shù)據(jù)

NodeJS如何發(fā)送buffer類型的數(shù)據(jù)

需求:

  整個需求可以抽象為Node.js通過readSteam讀取二進(jìn)制文件并通過post將其發(fā)送到后端服務(wù)器存儲到mongodb中。

目前的問題:

  通過createReadStream創(chuàng)建的讀流中讀取數(shù)據(jù),返回的為chunk類型的數(shù)據(jù),通過Node.js中的post上傳時(shí),數(shù)據(jù)丟失。

代碼如下:

/**
 * Created by Administrator on 2018/4/29.
 */
var fs = require('fs');
var http = require("http");
var queryString = require("querystring")

var filepath = "./mmp.txt";
var readSteam = fs.createReadStream(filepath);
readSteam.on("data",(chunk) => {
    console.log(chunk);
    let mydata = {"name":filepath, data: chunk};
    console.log(123)
    console.log(mydata);
    doapost(mydata);
})
function  doapost(data) {
    let contents = queryString.stringify(data);
    console.log("here");
    console.log(contents);
    let options = {
        host: "localhost",
        path: "/mytestpost/",
        port: 8000,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': contents.length
        }
    };
    let req = http.request(options, function (res) {
        res.on("data", function (chunk) {
            console.log(chunk.toString())
        });
        res.on("end", function (d) {
            console.log("end")
        });
        res.on("error", function (e) {
            console.log(e);
        })
    });
    req.write(contents);
    req.end();
}

運(yùn)行結(jié)果如下:

clipboard.png

可以看到上傳的時(shí)候name=.%2Fmmp.txt&data=
處buffer數(shù)據(jù)丟失了,請問各位碼友該如何解決?

回答
編輯回答
舊言

這是你querystring模塊用的不對
let contents = queryString.stringify(data);
Buffer類型的數(shù)據(jù)序列化沒了
文檔是這樣說的:
如果 obj 對象中的屬性的類型為 <string> | <number> | <boolean> | <string[]> | <number[]> | <boolean[]>,則屬性的值會被序列化。 其他類型的屬性的值會被強(qiáng)制轉(zhuǎn)換為空字符串。

2018年2月22日 04:57