简体   繁体   English

如何读取 Javascript 文件

[英]How to read a Javascript file

I have a file a /path/to/my_js_functions.js that contains a Javascript function my_js_functions() , amongst other functions.我有一个/path/to/my_js_functions.js文件,其中包含一个 Javascript 函数my_js_functions()以及其他函数。

How can I go about reading the function myJsFunction as a String in C++ ?如何在C++中将函数myJsFunction作为字符串读取?

I am looking for a way to get the whole function and only that function, and then contain it in a char *jsFunction .我正在寻找一种方法来获取整个函数并且仅获取该函数,然后将其包含在char *jsFunction

function myJsFunction(stringParam) {
  return stringParam   // The function returns a stringParam from the parameter
}  


function anotherJsFunction(stringParam) {
  return stringParam   // Another function
}  

Thank you all in advance.谢谢大家。

Using fstream, I would read line by line and check whether each line contains the sequence myJsFunction.使用 fstream,我将逐行读取并检查每一行是否包含序列 myJsFunction。 If a line does contain this sequence, then you begin aggregating to a string until you reach the next function (stopping after you reach the next keyword "function" or something of that sort).如果一行确实包含这个序列,那么你开始聚合到一个字符串直到你到达下一个函数(在你到达下一个关键字“函数”或类似的东西后停止)。 Note that using } as a keyword may not work as functions are likely to have multiple closing braces.请注意,使用}作为关键字可能不起作用,因为函数可能有多个右大括号。

Another possible solution could include identifying the end of the function by noticing that when a newline is immediately followed by non-whitespace a new function is beginning, assuming the code in your file is formatted where anything lower in scope is tabbed over correctly.另一个可能的解决方案可能包括通过注意到当换行符后紧跟非空白时一个新函数开始时来识别函数的结尾,假设您的文件中的代码被格式化,其中范围较低的任何内容都被正确地制表。

To do this you need to read your javascript code file and parse it.为此,您需要阅读您的 javascript 代码文件并解析它。 It is highly to use some parser library to do that like cashew , esprima-cpp .它是高度使用一些解析库做的,像腰果esprima-CPP I never used that before I never used any of this before, So I can't comment on that.我从来没有用过,我以前从来没有用过,所以我不能对此发表评论。

But here is some quick code for parser.但这里有一些解析器的快速代码。 You can start with this build on this to make it more robust.您可以从这个构建开始,使其更加健壮。

main.cpp主程序

#include <fstream>
#include <iostream>
#include <streambuf>
#include <string>
#include <vector>

std::string getFunction(const std::string &fileData, const std::string &name) {
  std::string ret;
  std::size_t start = 0;
  while (true) {
    const auto fNameStart = fileData.find(name, start);
    if (fNameStart != std::string::npos) {
      auto fStart = fileData.find_last_not_of(" ",fNameStart-1);
      if(fStart == std::string::npos){
        ret = "No Function Defination";
        break;
      }
      else {
        fStart = fStart-7;
        if(fileData.substr(fStart,8) == "function"){
            int openBraceCount = 0, closeBraceCount = 0;
            std::size_t fEnd = fNameStart + name.size();
            fEnd = fileData.find_first_of("{}", fEnd);
            while (fEnd != std::string::npos) {
                if (fileData.at(fEnd) == '{') {
                  openBraceCount++;
                } else {
                  closeBraceCount++;
                }
                if (openBraceCount == closeBraceCount) {
                  ret = fileData.substr(fStart, fEnd - fStart+1);
                  break;
                }
                fEnd++;
                fEnd = fileData.find_first_of("{}", fEnd);
            }
            if(!ret.empty()){
                break;
            }
            else if(openBraceCount != closeBraceCount){
                ret = "Function Parse Error";
                break;
            }
        }
        else{
            start = fNameStart + name.size();
        }
      }
    } else {
      ret = "No Function Defination";
      break;
    }
  }
  return ret;
}

int main(int argc, char **argv) {
  const std::string jsPath = "module.js";
  const std::vector<std::string> vecFuncNames{"funcA", "funcB", "funcC",
                                              "funcD", "funcE"};
  std::ifstream fs(jsPath);
  if (fs.is_open()) {
    std::string fileData((std::istreambuf_iterator<char>(fs)),
                         std::istreambuf_iterator<char>());
    for (auto &name : vecFuncNames) {
      std::cout << name << "\n" << getFunction(fileData, name) << std::endl;
    }
  }
  return 0;
}

module.js模块.js

function     funcA    (    ){
    funcC();  console.log("  Hello");funcB();
}function funcC(){funcB();console.log("Hello");funcA();}
function funcB(a,   b,   c){
    funcA();   setTimeout(function(){ alert("Hello"); }, 3000);funcC();
}
funcD();
function funcE(){{{{}}}

You can simply doing this你可以简单地这样做

For example /path/code.js is the path your code stored例如 /path/code.js 是你的代码存储的路径

Your code.js你的代码.js

function myJsFunction(stringParam) {
  return stringParam   // The function returns a stringParam from the parameter
}  


function anotherJsFunction(stringParam) {
  return stringParam   // Another function
}

module.exports = {
  myJsFunction,
  anotherJsFunction
}

And this is the file that you use to read the function you write这是您用来读取您编写的函数的文件

index.js索引.js

const code = require('/path/code.js');

console.log(code), it will be showing your whole code in your code.js file console.log(code),它将在您的 code.js 文件中显示您的整个代码

If you want to make it string, you can use syntax like this.如果你想把它变成字符串,你可以使用这样的语法。 Add this in code below on your index.js file and it will make string version of your code.在 index.js 文件的下面代码中添加它,它将使您的代码成为字符串版本。

String(code.myJsFunction)

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

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