Book Image

Learning Node.js for .NET Developers

Book Image

Learning Node.js for .NET Developers

Overview of this book

Node.js is an open source, cross-platform runtime environment that allows you to use JavaScript to develop server-side web applications. This short guide will help you develop applications using JavaScript and Node.js, leverage your existing programming skills from .NET or Java, and make the most of these other platforms through understanding the Node.js programming model. You will learn how to build web applications and APIs in Node, discover packages in the Node.js ecosystem, test and deploy your Node.js code, and more. Finally, you will discover how to integrate Node.js and .NET code.
Table of Contents (21 chapters)
Learning Node.js for .NET Developers
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Communicating via Ajax


Having created a game, we need a way of playing it. Since the whole point of a guessing game is that the word is secret, we don't want to send the whole word to the client. Instead, we just want to let clients know the length of the word and provide a way for them to verify their guesses.

To do this, we'll first need to expand our games service module:

class Game {
    constructor(id, setBy, word) {
        this.id = id;
        this.setBy = setBy;
        this.word = word.toUpperCase();
    }
    
    positionsOf(character) {
        let positions = [];
        for (let i in this.word) {
            if (this.word[i] === character.toUpperCase()) {
                positions.push(i);
            }
        }
        return positions;
    }
}

Now we can add two new routes to our games route:

const checkGameExists = function(id, res, callback) {
    const game = service.get(id);
    if (game) {
        callback(game);
    } else {
        res.status(404).send('Non-existent...