【问题标题】:how to implement this logic with node js如何用 node js 实现这个逻辑
【发布时间】:2016-02-14 05:05:44
【问题描述】:

我是 node.js 的新手,我想用 node.js 替换我用 C# 制作的应用程序,但是 node 的异步特性让我失望:

我想这样做:

1- Read N files, parse them and fill an array with the values from the files. 
2- Then every 30 seconds I need to read the files again and get the latest values in the file, added them to the array.
3- but immediately after step 1 is complete I can start a web server that will receive request from a browser. the server needs to send to the client some values form the array.

所以我需要网络服务器的连续循环(在加载初始值之后)能够回复客户端,同时我需要定期刷新数组

使用现有的应用程序我这样做:

1- read files , fill array
2- start a thread to server the clients (until app is closed)
3- start a thread to read the files again every N seconds and add new values to array  (until app is closed)

如果有任何想法,我将不胜感激,谢谢

【问题讨论】:

  • 你可能想看看expressjs.com
  • 寻求帮助以纠正尝试的代码在这里很好,但要求完整的实现不是。尝试一些东西,在你的问题中发布它,人们会咬你:)
  • 谢谢阿兰,但我并不是要求一个完整的实现,如果可能的话,只是一些让我开始的指针

标签: node.js


【解决方案1】:

我会使用流来监听这些文件的事件,这对性能更好,并且如果它们有任何数据,也可以监听事件(比如它是否有数据),然后我会读取它并将其通过管道传输到其他可写流(比如您的 http 响应),我更喜欢使用流和事件而不是使用计时器,例如:

var fs = require('fs');
var stream = fs.createReadStream(path);

stream.on('data',function(d){
  //just pipe it to your writable stream (you can use the http response)
});

希望对你有帮助!

【讨论】:

  • 谢谢 Bassam,...你的意思是,首先同步读取文件,填充数组,然后为当前文件设置一个流并订阅数据事件,当它被写入然后复制它数据到数组,这样数组会随着数据的进来而更新。那么还要创建“http-server-like”函数吗?这个想法是通过数据事件填充数组,当客户端请求数据时 node.js 将执行该部分?
  • 我的意思是使用流异步读取文件,因为它具有更好的性能并且它是基于事件的“Emmiter”,因此您可以检查流是否包含数据,并且可以将其通过管道传输到其他可写流(例如回应)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 2022-09-25
  • 1970-01-01
  • 2023-03-13
  • 2023-03-27
相关资源
最近更新 更多