简体   繁体   中英

Node.js Create new Routes from TCP Data

I have the following code, which is meant to capture JSON data through TCP, and then create a new route based on whatever is in the JSON file. So If one of my JSON files has:

{"pagename": "singsong"} 

Then I want my route to be mywebsite:8000/singsong and contain all data from whatever has the singsong pagename.

The problem I am facing is that my TCP data gets sent to all routes. So my route mywebsite:8000/singsong will contain JSON data that has {"pagename": "hazel"} , when I am trying to create new routes for each data.

My code, as is:

server.on("connection", function(socket){
    chunk = "";
socket.on('data', function(data){
    chunk += data.toString(); // Add string on the end of the variable 'chunk'
    d_index = chunk.indexOf(';'); // Find the delimiter

    // While loop to keep going until no delimiter can be found
    while (d_index > -1) {         
        try {
            string = chunk.substring(0,d_index); // Create string up until the delimiter
            json = JSON.parse(string); // Parse the current string
            app.set('fee', data);
            app.set('dee', json);
            console.log(json.pagename); // Function that does something with the current chunk of valid json.    
                app.get("/"+json.pagename, function(req, res){
                    res.writeHead(200, {'Content-Type': 'text/plain'});
                    res.write(JSON.stringify(req.app.get('dee')));
                    res.end();
                });
        }
        catch(e){
            console.log(e);
        }
        chunk = chunk.substring(d_index+1); // Cuts off the processed chunk
        d_index = chunk.indexOf(';'); // Find the new delimiter
    }      
});
        socket.on("close", function(){
            console.log("connection closed");
        });
});

Here's an example of capturing the json for each specific request in a closure variable (defined with let ) instead of using the app.set() that makes every single request conflict as they try to use the same storage location:

server.on("connection", function(socket) {
    let chunk = "";
    socket.on('data', function(data) {
        chunk += data.toString(); // Add string on the end of the variable 'chunk'
        let d_index = chunk.indexOf(';'); // Find the delimiter

        // While loop to keep going until no delimiter can be found
        while (d_index > -1) {
            try {
                let string = chunk.substring(0, d_index); // Create string up until the delimiter

                // define local variables that can be used in a closure
                let json = JSON.parse(string); // Parse the current string
                let localData = data;
                console.log(json.pagename); // Function that does something with the current chunk of valid json.    
                app.get("/" + json.pagename, function(req, res) {
                    res.writeHead(200, {
                        'Content-Type': 'text/plain'
                    });
                    res.write(JSON.stringify(json));
                    res.end();
                });
            } catch (e) {
                console.log(e);
            }
            chunk = chunk.substring(d_index + 1); // Cuts off the processed chunk
            d_index = chunk.indexOf(';'); // Find the new delimiter
        }
    });
    socket.on("close", function() {
        console.log("connection closed");
    });
});

Also, note that I define ALL your variables with let so they are properly scoped inside the function and not accidental globals which is likely to create hard-to-find bugs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM