2017-05-09 7 views
0

replace 변수에 ref 변수를 전달하는 방법은 무엇입니까? 나는nodejs의 fs에 대해 .replace에 변수를 삽입하는 방법

var ref = "www.facebook.com"; 

fs.readFile('text.html','utf8', function (err, data) { 
    if (err) { 
     return console.log(err); 
    } 

    var result = data.replace(/href="'+ref+'"/g, 'href="changeRef"'); 

    fs.writeFile('text.html', result, 'utf8', function (err) { 
     if (err) return console.log(err); 
     next(); 
    }); 

}) 

답변

0

사용 RegExp 클래스 대신 인라인 정규식 (B) 아래에있는 내 코드를보십시오.

data.replace(new RegExp('href="'+ref+'"', 'g'), ...)

는하지만 난 당신이 콜백 대신 일을 할 streams를 사용하는 것이 좋습니다. 다음과 같이됩니다.

const through2 = require('through2'); 
const fs = require('fs'); 
const writable = fs.createWriteStream('destPath'); 

fs 
    .createReadStream('path') 
    .pipe(new through2((data, enc, cb) => { 
     const chunk = data.toString(); 
     chunk = chunk.replace(new RegExp('foo', 'g'), 'bar'); 
     cb(null, chunk); 
    })) 
    .pipe(writable); 
+0

감사합니다. 내가 나중에 할께. – JerVi