用nodejs在文件上写http请求

Write http request on a file with nodejs

如何将 http 请求保存到文件中? 我使用 nodejs 作为服务器。我通过 ajax 发送数据,如下所示

user_info = 
    {
        system_info: [
            {'browesr': browser},
            {'brower-version': version},
            {'cookies': cookieEnabled},
            {'os': os},
            {'os-version': osVersion}
        ]
    }
}

$.ajax({
    url: 'http://127.0.0.1:4560',
    data: {"info" : JSON.stringify(user_info)},
    type: 'POST',
    jsonCallback: 'callback',
    success: function(data) {
        var ret = jQuery.parseJSON(data);
        $('#lblResponse').html(ret.msg);
        console.log('success');
    },
    error: function(xhr, status, error) {
        console.log('Error:' + error.message);
        $('#lblResponse').html('Error connecting to the server.');
    }
});

post 方法工作正常,在服务器端也接收数据。 我的问题是如何保存数据! 我搜索并找到了有关流媒体的内容。这是我的 nodejs 服务器代码。

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {

    console.log('Request Received');

    res.writeHead(200, {
        'Context-Type': 'text/plain',
        'Access-Control-Allow-Origin': '*'
    });

    req.on('data', function (chunk) {
        var rstream = fs.createReadStream(JSON.parse(chund));
        var wstream = fs.createWriteStream('info.txt');
        rstream.pipe(wstream);
        str += chunk;
        console.log('GOT DATA');
    });

    res.end('{"msg": "OK"}');
}).listen(4560, '127.0.0.1');
console.log('Server running at http://127.0.0.1:4560/');

我使用 fs 模块和流式传输,但根本没有用,"info.txt" 在同一目录中靠近服务器代码。

有人能帮帮我吗?

您已完成大部分内容。这是一个基于您的代码的工作示例:

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {

    console.log('Request Received');

    var body = '';

    res.writeHead(200, {
        'Context-Type': 'text/plain',
        'Access-Control-Allow-Origin': '*'
    });

    req.on('data', function (chunk) {
        body += chunk;
    });

    req.on('end', function() {
        fs.writeFile('file.json', body, 'utf8');
        res.end('{"msg": "OK"}');
    })

}).listen(4560, '127.0.0.1'); console.log('Server running at http://127.0.0.1:4560/');

这会将您发送的内容保存到名为 'file.json' 的文件中。

您还需要对您的 Ajax 请求进行一些小的更改:

url: 'http://127.0.0.1:4560',
data: JSON.stringify({"info" : user_info}),
contentType: "application/json",
type: 'POST',
jsonCallback: 'callback',

如果你想修改你写入文件的内容,那么你可以这样:

req.on('end', function() {
    var parsedJson = JSON.parse(body);
    fs.writeFile('file.json', JSON.stringify(parsedJson.info), 'utf8');
    res.end('{"msg": "OK"}');
})

如果你想附加文件而不是覆盖它,那么你可以这样做:

req.on('end', function() {
    var parsedJson = JSON.parse(body);
    // Read and parse the JSON file
    var file = require('file.json');
    file[parsedJson.someKindOfID] = parsedJson;
    fs.writeFile('file.json', JSON.stringify(file), 'utf8');
    res.end('{"msg": "OK"}');
})

但这取决于你在文件中的数据结构。