티스토리 뷰
참고 http://stackoverflow.com/a/30545872
나의 경우 Express, Postgresql 사용하여 살짝 변경함.
프로젝트 Root dir에 db.js 파일을 생성한다.
나의 경우 postgresql을 사용하였기 때문에 bluebird와 pdb-pomise를 require했음.
var promise = require('bluebird');
var pgp = require('pg-promise')({promiseLib: promise});
var conString = "postgres://USER:PASS@HOST/DBNAME";
var db = pgp(conString);
module.exports = db;
위와 같이 하면 DB 연결은 끝
DB를 사용할 파일에서 require('/DB'); 후 다음처럼 쓰면됨.
db.any('SELECT * FROM table')
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ALL'
});
})
.catch(function (err) {
return next(err);
});
# node.js 문서에 require('foo')를 할때마다 정확히 같은 객체가 반환된다고 적혀있음.
# every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
'Programming > Web' 카테고리의 다른 글
JWT (Json Web Token) (0) | 2017.01.05 |
---|---|
[Node.js/Express] interceptor 구현하기 (0) | 2017.01.04 |
[node.js/express] set default path (base url, prefix url) (0) | 2016.12.30 |
[Node.js] 환경변수 쓰고 읽기 (WebStorm, RubyMine) (0) | 2016.12.29 |
NodeUnit 설치 및 RubyMine 설정 (0) | 2016.12.28 |