为什么不同的node.js会话共享变量? [英] Why do different node.js sessions share variables?

查看:137
本文介绍了为什么不同的node.js会话共享变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的程序:

  var express = require('express'); 

var app = express.createServer();

var count = 0;

app.get(/,function(req,res){
res.send(count.toString());
count ++;
}) ;

app.listen(3000);

当我在两个不同的浏览器中打开它时,第一个显示 0 ,第二个显示 1



为什么?它们是不同的会话,所以我希望node.js为他们使用不同的子进程。使用PHP,我的理解是共享变量应该使用数据库来实现。



为什么node.js没有任何外部存储?它是一个单进程,但是多个线程?



如何声明属于特定会话的变量?

解决方案

Node.js是单一过程。



您的代码在单个进程中运行在eventloop的顶部。 >

JavaScript是单线程的。你运行的每一段代码都是单线程的。 Node.js是快速和缩放的,因为它不是在IO上阻止(IO是瓶颈)。



基本上你运行的任何javascript单螺纹JavaScript是继承单线程的。



当您调用nodeJS API的一部分时,它会在C ++级别内部使用线程,以确保可以向您发送传入的HTTP请求服务器或发回您的文件进行文件访问。这使您可以使用异步IO



至于会话

  app.use(express.session({secret:Some _proper_ secret})); 
...
app.get(/,function(req,res){
if(req.session.count == null){
req.session。 count = 0;
}
res.send(req.session.count);
req.session.count ++;
});


Here is a simple program:

var express = require('express');

var app = express.createServer();

var count = 0;

app.get("/", function(req, res) {
    res.send(count.toString());
    count++;
});

app.listen(3000);

When I open it in two different browsers, the first displays 0 and the second displays 1.

Why? They are different sessions so I expect node.js use different child processes for them. My understanding, with PHP, is that sharing variables should be implemented using databases.

Why can node.js do this without any external storage? Is it a single-process but multiple threads?

How do I declare a variable that belongs to a specific session?

解决方案

Node.js is single process.

Your code runs in a single process ontop of an eventloop.

JavaScript is single threaded. Every piece of code you run is single threaded. Node.js is fast and scales because it does not block on IO (IO is the bottle neck).

Basically any javascript you run is single threaded. JavaScript is inherantly single threaded.

When you call parts of the nodeJS API it uses threading internally on the C++ level to make sure it can send you the incoming requests for the HTTP servers or send you back the files for the file access. This enables you to use asynchronous IO

As for sessions

app.use(express.session({ secret: "Some _proper_ secret" }));
...
app.get("/", function(req, res) {
    if (req.session.count == null) {
        req.session.count = 0;
    }
    res.send(req.session.count);
    req.session.count++;
});

这篇关于为什么不同的node.js会话共享变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆