Node.js:全局变量是否在实例之间共享?

use*_*421 1 javascript asynchronous global-variables node.js async-await

我有这个代码:

app.post('/pst', function(req, res) {
        var url = req.body.convo;


                myAsyncFucntion(url).then(result => { 
                    console.log('TAKE A LOOK AT THIS!');


                    //transforming array to string to pass to Buffer.from()
                    //then we remove ',' with newlines, so each index of array is a new line
                    var str = result.toString();
                    result = str.split(',').join('\r\n');


                    //clever way to send text file to client from the memory of the server
                    var fileContents = Buffer.from(result, 'ascii');
                    var readStream = new stream.PassThrough();
                    readStream.end(fileContents);
                    res.set('Content-disposition', 'attachment; filename=' + fileName);
                    res.set('Content-Type', 'text/plain');
                    readStream.pipe(res);

                    //garbage collecting. i don't know if it's neccessary
                    result = '';
                    str = '';

                }).catch(err => {
                    console.log(err);
                    res.render('error.ejs');
                })
});
Run Code Online (Sandbox Code Playgroud)

此代码将运行一个异步函数,并将内存中的一些数据作为文本文件提供给用户。我打算使用套接字并通知客户端工作已完成。客户端将输入一个链接并下载一个文件。

所以我打算取局部变量结果并将其导出到全局变量中。这样,app.get()将有权访问它,并且当用户点击该链接时,它将提供该文件。

但是一位用户告诉我,全局变量在实例之间共享。

这是真的?因此,如果两个(或更多)用户尝试同时获取他们的结果,全局变量将是相同的

对于他们两个?

Que*_*tin 5

这是真的?

是的。(嗯,实际上是的。真正的答案是首先没有“多个实例”:您有一个服务器,多个用户正在向其发出多个请求。)

如果要将数据与特定浏览器会话相关联,请使用会话(NPM 模块来处理 Express 存在的会话)。