使用Node.js将HTTP请求写入文件

3
如何将http请求保存到文件?我正在使用Node.js作为服务器。我通过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方法正常工作,在服务器端也接收到了数据。我的问题是如何保存数据!我搜索并找到了一些关于流的内容。这是我的Node.js服务器代码。

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”在与服务器代码相同的目录中。
有人能帮帮我吗?
1个回答

3
你已经完成了大部分的工作。以下是一个基于你的代码的可行示例:

你已经快要成功了。这是一个基于你的代码的可行示例:

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

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

谢谢伙计!只有一个问题,当我打开file.json文件时,保存的数据是这样的:info=%7B%22system_info%22%3A%5B%7B%22browser....,为什么没有像正常的json一样显示数据呢? - Abbas Alipour
在您的Ajax请求中,尝试使用data: JSON.stringify({"info" : user_info})并设置contentType: "application/json" - dan
正确!但还有一个问题,当您在新的操作系统或Web浏览器中打开页面时,服务器会删除先前的JSON并写入新的JSON,我该如何追加数据? - Abbas Alipour
我已经更新了答案,并提供了一个示例。或者,您可以为每个请求创建一个新文件并更改文件名。 - dan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接