access log파일의 Line 업데이트를 감시하고, 한 줄씩 다른 애플리케이션으로 전송하고자 한다. 해당 기능을 Node.js로 구현하기 위해 fs 라이브러리가 필요하다 들었다. 감시 기능을 구현하기 앞서, fs 라이브러리가 무엇인지 살펴보고 실습을 해본다. 해당 글은 다음과 같은 순서로 되어있다.
- 정의
- 종류
- 사용법
- read, write 실습하기
정의
파일 시스템으로 접근과 상호작용 등 유용한 기능을 제공한다. 설치할 필요없이 require
하여 사용가능하다.
const fs = require('fs');
종류
fs.access()
: check if the file exists and Node.js can access it with its permissionsfs.appendFile()
: append data to a file. If the file does not exist, it's createdfs.chmod()
: change the permissions of a file specified by the filename passed. Related:fs.lchmod()
,fs.fchmod()
fs.chown()
: change the owner and group of a file specified by the filename passed. Related:fs.fchown()
,fs.lchown()
fs.close()
: close a file descriptorfs.copyFile()
: copies a filefs.createReadStream()
: create a readable file streamfs.createWriteStream()
: create a writable file streamfs.link()
: create a new hard link to a filefs.mkdir()
: create a new folderfs.mkdtemp()
: create a temporary directoryfs.open()
: opens the file and returns a file descriptor to allow file manipulationfs.readdir()
: read the contents of a directoryfs.readFile()
: read the content of a file. Related:fs.read()
fs.readlink()
: read the value of a symbolic linkfs.realpath()
: resolve relative file path pointers (.
,..
) to the full pathfs.rename()
: rename a file or folderfs.rmdir()
: remove a folderfs.stat()
: returns the status of the file identified by the filename passed. Related:fs.fstat()
,fs.lstat()
fs.symlink()
: create a new symbolic link to a filefs.truncate()
: truncate to the specified length the file identified by the filename passed. Related:fs.ftruncate()
fs.unlink()
: remove a file or a symbolic linkfs.unwatchFile()
: stop watching for changes on a filefs.utimes()
: change the timestamp of the file identified by the filename passed. Related:fs.futimes()
fs.watchFile()
: start watching for changes on a file. Related:fs.watch()
fs.writeFile()
: write data to a file. Related:fs.write()
파일 읽기 사용법
파일 읽기는 다음과 같은 문법을 가지고 있다.
fs.readFile(path[, options], callback)
fs.readFileSync(path[, options])
동기 방식
const text = fs.readFileSync("./access.log", "utf-8");
console.log(text);
동기적으로 구동되며 예외처리 방식으로 try ~ catch 구문을 사용해야 한다. 예시는 다음과 같다.
try{
const text = fs.readFileSync("./access.log", "utf-8");
console.log(text);
}
catch(err){
console.log(err);
}
비동기 방식
fs.readFile('./access.log', 'utf8', (err, data) => {
if(err){throw err}
console.log(data);
});
비동기적으로 구동되며 예외가 발생하면 callback 함수의 매개변수 err에 값이 전달되므로, err에 값이 있으면 err를 리턴해주는 if문으로 예외처리가 가능하다.
프로미스 방식
비동기 방식의 처리에서 자칫 콜백 지옥에 빠질 수 있다. 모든 발생할 수 있는 err에 조건을 달아주어야 하기 때문에 코드가 복잡해질 수 있다. 그래서 promise-based API를 제공해준다.
const fs = require('fs/promises');
async function example(){
const fileName = "./access.log"
try {
const data = await fs.readFile(fileName, "utf-8");
console.log(data);
}catch(err){
console.log(err);
}
};
example()
try {~}에 원하는 것을 비동기적으로 쭉 실행시키고 에러가 발생하면 한 번에 catch 하는 것이다.
실습
기본적인 사용법을 익혔으니, fs.watchFile()
실습해보자.
fs.watchFile()
- 문법:
fs.watchFile(filename[, options], listener)
- filename을 감시해 listener라는 콜백 함수의 curr, prev 매개변수로 전달하고, 결괏값을 리턴하는 함수이다. 이때 매개변수에는
<fs.stat>
이라는 정보 값이 담긴 Object인데, 다음과 같은 정보가JSON
형태로 저장된 객체이다.
Stats {
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atimeMs: 1318289051000.1,
mtimeMs: 1318289051000.1,
ctimeMs: 1318289051000.1,
birthtimeMs: 1318289051000.1,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
- 예제 코드는 다음과 같다.
const fs = require('fs')
fs.watchFile("./access.log", (curr, prev) => {
console.log(`파일 변동 후 시간: ${curr.mtime}`);
console.log(`파일 변동 전 시간: ${prev.mtime}`);
});
- 출력은 다음과 같다.
- 파일이 변동된 것을 잘 감지할 수 있다! 이 애플리케이션이 파일 변동을 감지하고,
fs.readFile
을 이용해 마지막 accesslog를 읽어 들여 http body에 실어 다음 애플리케이션으로 로그를 전송할 수 있지 않을까? 생각이 든다
'Programming Language > JavaScript' 카테고리의 다른 글
[JS]재귀함수 예제3 (0) | 2022.05.15 |
---|---|
[JS]재귀함수 예제2 (0) | 2022.05.15 |
[JS]재귀함수 예제1 (0) | 2022.05.13 |
[JS]재귀함수 예제 (0) | 2022.05.11 |
[JS]arr의 다양한 메소드 (0) | 2022.05.08 |