| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
- Git
- event-driven
- window
- multidex
- MEAN stack
- iIntelliJ
- proguard
- OOP
- Express
- MaridDB
- Linux
- rest-assured
- 64k method
- centos
- Java
- Mongoose
- PBKDF2
- ssh key
- instance
- Mongo
- Android
- react-native
- API테스트
- elemMatch
- Setup
- pbkdf2-password
- node
- 다중 서버 명령
- Modulization
- memory structure
- Today
- Total
천줄코딩도 한 걸음부터
Node.js Mysql(MariaDB) 모듈화하기 본문
프로젝트에서 Node.js에 MariaDB를 사용하여 모듈을 개발하고 있습니다.
Mysql과 이름이 다른 MariaDB 라지만 쿼리문에는 큰 차이가 없었습니다.
모듈 개발 프로젝트를 진행하다보니 Mysql config, connect, sql 코드들을 app.js에 모두 넣다보니 가독성이 점점 떨어졌습니다.
그래서 굳이 각 기능들을 모듈로 분리해 눈과 머리가 편안할 수 있도록 개발을 진행하기로 했습니다.
0. mysql 설치
Node.js에서 Mysql을 사용하려면 설치부터 해야죠.
작업 디렉토리로 이동 후 아래 명령을 통해 mysql 모듈을 받아옵니다. --save 옵션은 package.json에 추가하는 구문인데 생략 가능합니다.
$ npm install mysql --save
1. db_config.js
db 연결 정보를 포함하는 부분입니다. (사실 이 부분은 굳이 나누지 않아도 되지 않나 생각됩니다.)
module.exports = (function() {
return {
host: "xxx.xxx.xxx.xxx",
user: "your_name",
password: "your_password",
database: "your_database"
}
})();
2. db_connect.js
connection pool을 포함하는 부분입니다. config 파일을 불러와 해당 정보를 매핑시켜 connection pool을 생성합니다.
(사용하시는 용도에 따라 connection pool이 아닌 connection을 사용하셔도 무방하다고 생각합니다.)
end function은 외부에서 pool을 close 할 수 있도록 하기 위해 추가했습니다.
var mysql = require('mysql');
module.exports = function () {
var config = require('./db_config'); // ./는 현재 디렉토리를 나타냅니다
var pool = mysql.createPool({
host: config.host,
user: config.user,
password: config.password,
database: config.database
});
return {
getConnection: function (callback) { // connection pool을 생성하여 리턴합니다
pool.getConnection(callback);
},
end: function(callback){
pool.end(callback);
}
}
}();
3. db_sql.js
connect를 가져와 getConnection을 호출합니다. 이 getConnection은 callback 함수로 connection 객체를 반환합니다.
이 객체를 통해 정의한 sql을 query할 수 있습니다. query는 기본적인 select문을 가져왔습니다.
query callback 함수에서 connection을 release해줍니다. 꼭 쿼리가 끝난 후 release 해주셔야 문제가 발생하지 않습니다.
이 후 결과값을 바탕으로 적절한 콜백 처리를 해줍니다.
var pool = require('./db_connect');
module.exports = function () { return { select: function(callback){ pool.getConnection(function(err, con){ var sql = 'select name, age from user_table order by 1 desc'; con.query(sql, function (err, result, fields) { con.release(); if (err) return callback(err); callback(null, result); }); }); }, pool: pool } };
4. app.js
sql을 가져와 쿼리를 수행합니다.
select 결과를 반환한 후 pool.end를 통해 connection pool을 닫아줍니다. 닫지 않으면 프로그램이 종료되지 않습니다.
var sql = require('./db_sql')();
console.log('app.js started');
sql.select(function(err, data){
if (err) console.log(err);
else console.log(data);
db_sql.pool.end(function(err){
if (err) console.log(err);
else {
console.log('Connection pool has closed');
console.log('app.js finished');
}
});
});
간단하게 Mysql(MariaDB)과 Node.js 연동하는 모듈을 기능별로 모듈화 해봤습니다.
문제되는 점이나 보완해야할 점 등 댓글로 남겨주세요. 감사합니다.
'Others' 카테고리의 다른 글
| rest-assured Java API 테스팅 라이브러리 (0) | 2023.10.05 |
|---|---|
| Mac에서 쉘 스크립트로 다중 서버에 같은 명령 내리기 (0) | 2018.07.04 |
| Node.js 대상 디렉토리 내의 모든 파일 읽어오기 (2) | 2017.11.09 |
| Python Zip 파일로 압축하기 (0) | 2017.11.09 |
| Node.js Crypto 사용하여 파일로부터 Hash값 얻어오기 (0) | 2017.11.09 |