2017-04-05 34 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