Visualizzazione dei risultati da 1 a 2 su 2

Discussione: Node.js file not found

  1. #1

    Node.js file not found

    ciao!
    sto avendo un problema con node.js.
    in pratica ho un file server.js che dovrebbe mandare in output il contenuto di un file html.
    esattamente ho:
    -server.js
    -content/test.html

    questo il contenuto del file js:
    codice:
    var http = require('http');
    var fs = require('fs');
    
    function handleIncomingRequest(req, res) {
        if (req.method.toLowerCase() === 'get' && req.url.substring(0, 9) === '/content/') {
            serveStaticFile(req.url.substring(9), res);
        } else {
            res.writeHead(404, {"Content-Type": "application/json"});
            var out = {error: "not_found", message: "'" + req.url + "' not found"};
            res.end(JSON.stringify(out) + "\n");
        }
    }
    
    function serveStaticFile(file, res) {
        var rs = fs.createReadStream(file);
        var ct = contentTypeForPath(file);
        res.writeHead(200, {"Content-Type": ct});
    
        rs.on(
                'readable',
                function() {
                    var d = rs.read();
                    if (d) {
                        if (typeof d === 'string') {
                            res.write(d);
                        } else if (typeof d === 'object' && d instanceof Buffer) {
                            res.write(d.toString('utf8'));
                        }
                    }
                }
        );
    
        rs.on(
                'error',
                function(e) {
                    res.writeHead(404, {"Content-Type": "application/json"});
                    var out = {error: "not_found", message: "'" + file + "' not found"};
                    res.end(JSON.stringify(out) + "\n");
                    return;
                }
        );
    
        rs.on(
                'end',
                function() {
                    res.end();
                }
        );
    }
    
    function contentTypeForPath(file) {
        return "text/html";
    }
    
    var s = http.createServer(handleIncomingRequest);
    s.listen(8080);
    se sul browser vado su http://192.168.1.130:8080/content/test.html ottengo sempre questo errore:
    codice:
    {"error":"not_found","message":"'test.html' not found"}
    però non capisco il perchè!

  2. #2
    prendendo spunto da qua http://docs.nodejitsu.com/articles/a...te-read-stream , ho risolto così:
    codice:
    serveStaticFile(__dirname + req.url, res);
    ciao!!

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.