简体   繁体   English

将Node.js中的createReadStream中的数据代入

[英]Substitute data in createReadStream in Node.js

I'm not really sure I'm asking the right question here... so please don't attack me.我不太确定我在这里问的是正确的问题......所以请不要攻击我。

I'm creating my own asynchronous callback library for a type of tracking implementation.我正在为一种跟踪实现创建自己的异步回调库。 The user must install a piece of code on their site that contains a unique account number.用户必须在他们的网站上安装一段包含唯一帐号的代码。 Think Google Analytics.想想谷歌分析。

The library call reaches out to my node server and passes along the account id in the query parameter.库调用到达我的节点服务器并传递查询参数中的帐户 ID。

Node responds with the analytics library so various tracking functions can be called on the user's site. Node 使用分析库进行响应,因此可以在用户站点上调用各种跟踪功能。

My question is, how can I modify my static tracking library that gets streamed back to the user's page based on the query parameter?我的问题是,如何修改我的 static 跟踪库,它根据查询参数流回用户页面? For instance, once the account ID is read off the query string, I do a DB look-up to find some values in the library that are specific to that user and would like to modify particular functions in my library appropriately.例如,一旦从查询字符串中读取帐户 ID,我就会执行数据库查找以在库中查找特定于该用户的一些值,并希望适当地修改我的库中的特定函数。

I'm reading a static file off my local server with: fs.createReadStream("./file.js");我正在使用以下命令从本地服务器读取一个 static 文件:fs.createReadStream("./file.js");

How can I modify that file to substitute certain values within for others?我如何修改该文件以将其中的某些值替换为其他值?

Or should I be reading the file in to an in-memory object at startup and then simply writing out modified data via the response object?或者我应该在启动时将文件读入内存 object,然后通过响应 object 简单地写出修改后的数据?

You could simply use eco or ejs templates for this, but for just to have an idea or if you prefer to make this yourself, I think you should make a template based on your file.js and then write user specific parts of the code with the corersponding data using a set of regular expressions.您可以为此简单地使用ecoejs模板,但只是为了有一个想法,或者如果您更喜欢自己制作这个,我认为您应该根据您的file.js制作一个模板,然后编写用户特定的代码部分使用一组正则表达式的相应数据。

For example:例如:

template.js模板.js

var get_user = function () {
  return "Hi %%USER_NAME%%"
}

then req.send()` the content of template.js replaced something like this:然后 req.send()` template.js的内容替换了这样的东西:

var result = cached_template_data;
if (!result) {
  fs.readFile("./template.js", function (err, data) {
    result = cached_template_data = data;
    if (!err) {
      result = result.replace(/%%USER_NAME%%/g, user.name)
      res.send(result);
    } else {
      // Big oops
      res.send({error:true}, 500);
    }
  })
} else {
  result = result.replace(/%%USER_NAME%%/g, user.name)
  res.send(result);
}

UPDATE更新

Consider caching whenever possible by the way...顺便考虑尽可能缓存...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM