2017-05-20 1 views
0

기존 파일의 N 값을 자리 표시 자로 바꿔야합니다.nodeJS 하나의 파일에서 여러 값 바꾸기

ExpressJS 앱의 게시물 요청이 실행되면 파일의 자리 표시 자 값을 변경해야합니다. 예를 들어

SASS 파일 :

router.post('/', function(req, res) { 

    fs.readFile('main.scss', 'utf8', (err, data) => { 
     if(err) { 
      console.log('An error occured', err); 
     } 

     backgroundColorToReplace = data.replace(/##backgroundColor##/g, 
     req.body.backgroundColor); 
     // This value has to be replaced as well 
     textColorToReplace = data.replace(/##textColor##/g, req.body.textColor); 

     fs.writeFile('main.scss', backgroundColorToReplace, (err) => { 
      if(err) { 
       console.log('An error occured', err); 
      } 

      console.log('Colors successfully changed'); 
     }); 
    }); 

    res.json({ 
     textColor: req.body.textColor, 
     backgroundColor: req.body.backgroundColor 
    }); 
}); 

가 어떻게이 문제를 해결할 수 있습니다 : 1 개 교체와 함께 잘 작동

$textColor: ##textColor##; 
$backgroundColor: ##backgroundColor##; 

그리고 내 기능? 방법이 있습니까?

+0

또 다른 모든 향후 사용자의 모든 향후 요청에 대해 'textColor'및 'backgroundColor'가 변경된다는 점에 유의하십시오. 그게 당신이 의도 한 것입니까? 아니면 사용자 별 설정으로되어 있습니까? – jfriend00

+0

@ jfriend00 네, 알고 있습니다. nodeJS에서 프로그래밍에 대해 좀 더 이해하고 플레이하기위한 테스트 케이스이다. – pkberlin

답변

3

글쎄, 같은 데이터 세트에서 replace()을 실행하지 않고 첫 번째 변경 사항 만 기록합니다. 자바 스크립트 문자열은 불변이므로 .replace()은 원래 데이터를 변경하지 않습니다.

// ... 

data = data.replace(/##backgroundColor##/g, req.body.backgroundColor); 
data = data.replace(/##textColor##/g, req.body.textColor); 

fs.writeFile('main.scss', data, (err) => { 

// etc. 
+0

감사합니다. 그게 내가 원하는거야 :) – pkberlin

관련 문제