【问题标题】:Node.js will create file but not write to it using the following code. node-186364e.exe on windows xpNode.js 将使用以下代码创建文件但不写入文件。 Windows XP 上的 node-186364e.exe
【发布时间】:2011-09-05 16:04:56
【问题描述】:
var
http = require('http'),
fs = require('fs'),
buffer,
working = 'notworking',
options = {
        host: '202.138.228.141',
        port: 8080,
        path: 'www.google.com'
};

http.get(options, function(res) {

        if (res.statusCode < 400) working = 'working';
        writeResults(options);

}).on('error', function (e) {

        writeResults(options);

});

function writeResults (options) {
        buffer = '\n' + options.host + ':' + options.port + ':' + working;
        fs.open('results.ht', 'a', function (err, fd) {
                fs.write(fd, buffer, function (e, written, buf) {
                        fs.closeSync(fd);
                });
        });
}

【问题讨论】:

    标签: node.js windows-xp


    【解决方案1】:

    如果你想从 http.get 写入数据,你会这样做:

    http.get(options, function(res) {
        var data = '';
        res.on('data', function(d) {
            data += d;
        });
        res.on('end', function(e) {
            writeResults(options, working, data);
        });
    }).on('error' function(e) {
       writeResults(options, 'ERROR', null);
    });
    

    然后可能将 writeResults 更改为:

    function writeResults(options, working, data) {
        buffer = '\n' + options.host + ':' + options.port + ':' + working;
        if (data) {
            buffer += '\n' + data;
        }
        fs.open('results.ht', 'a', function (err, fd) {
            fs.write(fd, buffer, function (e, written, buf) {
                fs.closeSync(fd);
            });
        });
    };
    

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 2018-12-02
      • 2016-09-25
      相关资源
      最近更新 更多