FS :

2017-01-10 1 views
0

주어진 다음의 파일을 다른 파일 내용으로 파일 내용을 대체 :FS :

127.0.0.1 localhost 

프로젝트 a.hosts을

호스트

127.0.0.1 project-a 

프로젝트 b.hosts

127.0.0.1 project-b 

가장 쉬운 w는 무엇입니까? 호스트 파일 내용을 다른 지정된 파일로 대체하려면 ay를 노드의 FS를 통해 사용 하시겠습니까?

답변

1

node.js의 fs 모듈을 사용하면됩니다. 여기에는 두 가지 방법이 있습니다. 하나는 비동기 함수를 사용하고 다른 하나는 동기 아날로그를 사용하는 것입니다. 이것은 매우 간단합니다.

질문을하기 전에 StackOverflow를 더 철저하게 검색하는 것이 좋습니다. 이런 종류의 질문은 매우 일반적이기 때문에. 예를 들어 this answer을 확인하십시오 ...

const fs = require('fs'); 

// async 
function replaceContents(file, replacement, cb) { 

    fs.readFile(replacement, (err, contents) => { 
    if (err) return cb(err); 
    fs.writeFile(file, contents, cb); 
    }); 

} 

// replace contents of file 'b' with contents of 'a' 
// print 'done' when done 
replaceContents('b', 'a', err => { 
    if (err) { 
    // handle errors here 
    throw err; 
    } 
    console.log('done'); 
}); 


// sync - not recommended 

function replaceContentsSync(file, replacement) { 

    var contents = fs.readFileSync(replacement); 
    fs.writeFileSync(file, contents); 

} 

replaceContentsSync('a', 'b');