갱신

2017-10-18 2 views
0
I have on abc.js file in node side.Having below content: 

abc.js갱신

"use strict"; 
// Test specific configuration 
// =========================== 
module.exports = { 
    port: process.env.PORT || 8101, 
    api:{xyz:"old"} 
} 



while using below code to update api->xyz value : 

nodetest.js

덮어 abc.js에서
var fs = require('fs'); 
var fileName = './abc.js'; 
var file = require(fileName); 

file.api.xyz= "new"; 

fs.writeFile(fileName, JSON.stringify(file, null, 2), function (err) { 
    if (err) return console.log(err); 
    console.log(JSON.stringify(file)); 
    console.log('writing to ' + fileName); 
}); 

I am getting below output in abc.js 

{ 
    "port": 8101, 
    "api":{"xyz":"new"} 
} 

, "엄격한 사용", "module.exports" 코멘트가 없습니다. 어떻게 abc.js 파일의 모든 내용을 동일한 형식으로 "xyz"값의 변경된 값으로 유지할 수 있습니까?

원하는 출력은 다음과 같아야합니다

abc.js 난 당신이 수동으로 require에게 그들을, 유일한 것은 당신이로 가져 오는 경우 이후에 다시 추가해야합니다 생각

"use strict"; 
// Test specific configuration 
// =========================== 
module.exports = { 
    port: process.env.PORT || 8101, 
    api:{xyz:"new"} 
} 

답변

0

당신의 파일은 수출이다 (이 경우, 업데이트중인 객체입니다.) 그렇지 않으면

const output = ` 
"use strict"; 
// Test specific configuration 
// =========================== 
${JSON.stringify(file)} 
` 
fs.writeFile(fileName, output, ... 

, 당신은 결과 문자열을 업데이트 fs.readFile를 사용해야 할 것 , 그리고 그것을 쓴다.