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

Integrating Socket.IO with Express


So far, apart from sharing the same server, the Socket.IO and Express parts of our application are completely independent. While it's good that they are loosely coupled, some cross-cutting concerns may be relevant to both.

For example, both parts of our application should have a mutually consistent way of identifying the current user. This is especially important if they are to come together to provide a single coherent user experience.

First, let's extend our user middleware to provide the current user's name as well as their ID, by looking them up in the user service as given here src/middleware/users.js:

'use strict';

module.exports = (service) => {
    const uuid = require('uuid');

    return function(req, res, next) {
        let userId = req.cookies.userId;
        if (!userId) {
            userId = uuid.v4();
            res.cookie('userId', userId);
            req.user = {
                id: userId
            };
            next();
      ...