2017-04-05 70 views
1

我有一个名为“file.php”文件包含这样的行(不仅):重写文件内容为JSON准备

... 
define("META_PAGE_BRAND_HOME_TITLE","esta es la Marca"); 
define("META_PAGE_BRAND_HOME_DESCRIPTION","Conoce nuestra Marca y empieza con la web "); 
define("META_PAGE_BRAND_HOME_KEYWORDS","Marca Logo Mision"); 
... 

我希望得到这样的:

{ 
"meta_page_brand_home_title":"esta es la Marca", 
"meta_page_brand_home_description":"Conoce nuestra Marca y empieza con la web ", 
"meta_page_brand_home_keywords":"Marca Logo Mision" 
} 

我想重写那些只有以“define(”)开头的行或者一个新文件,第一部分中的大写字母应该是小写字母。我知道我应该做一些类似this的事情,但我并不那么敏锐。任何帮助将不胜感激。

回答

1

你必须做的第一步是实际读取文件的内容,这可以使用fs.readFile()完成。

fs.readFile('path/to/file.php', function(err, fileContents) { 
    if (err) { 
     throw err; 
    } 
    // `fileContents` will then contain the contents of your file. 
}); 

一旦你有你的文件的内容,您将需要使用正则表达式找到define()电话和之前使用它里面的代码:

var regex = /define\((".*?"), *(".*?")\)/g; 
var match = regex.exec(fileContents); 
// `fileContents` contains the contents of your file. 

while(match) { 
    // match[1] will contain the first parameter to the "define" call 
    // match[2] will contain the second parameter to the "define" call 
    // use match[1] and match[2] however you want, like log it to the console: 
    console.log(match[1].toLowerCase() + ':' + match[2] + ','); 

    // Look for the next match 
    match = regex.exec(fileContents); 
} 
+0

是,就是这样,感谢阿内尔 – MikRut