반응형

파일 분리를 잘못했을 때 나타날 수 있는 Error

TypeError: Cannot read properties of undefined (reading 'collection')

 

mongodb.js 파일을 만들고 아래와 같이 db 정보를 export 하면 다른 파일에서 db를 접근할 때 위와 같은 오류가 난다.


const MongoClinet = require('mongodb').MongoClient;
var db;
MongoClinet.connect(
    process.env.DB_URL
    ,(err, client)=>{
        if(err) return console.log(err);

        db = client.db('DBname');

});


module.exports = db;
 
 

왜냐하면 DB 연결 설정은 비동기적으로 처리되므로 연결이 완료되지 않은 상태에서 module.exports = db; 코드가 실행될 수 있다. 그래서 undefined인 db 변수를 exports 했기 때문에 다른 파일에서 db를 사용할 수 없다.

 

Solution

mongodb.js에 DB 연결 설정하는 함수, DB 정보를 가져오는 함수를 객체로 만들고 app.js(메인 서버 코드)에서는 DB 연결 설정 함수를 호출하고 연결이 정상적으로 완료되면 콜백 함수로 그때 나머지 서버 코드를 호출하도록 하면 된다.

 

app.js가 아닌 다른 파일에서 db 정보를 얻고 싶으면 getDB함수만 호출하면 된다. 왜냐하면 app.js에서 이미 DB 연결 설정 함수를 호출했고 require은 항상 오직 한 번만 로드가 되기 때문에 db정보를 그대로 쓸 수 있다.

 

 

 [lib/mongodb.js]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const MongoClinet = require('mongodb').MongoClient;
let _db;
 
const connectDB = (callback) => {
    MongoClinet.connect(process.env.DB_URL, (err, client) => {
        _db = client.db('DBname');
        return callback(err);
    });
 
}
 
const getDB = () => _db;
const disconnectDB = () => _db.close();
 
module.exports = { connectDB, getDB, disconnectDB };
 
 
cs

 

 

[app.js]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const express = require('express');
const app = express();
 
 
const MongoDB = require('./lib/mongodb.js');
MongoDB.connectDB((err) => {
    if (err) return console.error(err);
 
 
    // Connect to MongoDB and put server instantiaition code inside
    // because we start the connection first
 
 
     app.listen(process.env.PORT, () => {
        console.log(`listening on ${process.env.PORT}`);
    });
 
 
});
 
cs

 

[다른 파일에서 db 정보 얻기]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var router = require('express').Router();
var MongoDB = require('../lib/mongodb.js');
var db = MongoDB.getDB();
 
router.get('/', (req, res)=>{
    db.collection('post').find().toArray((err, result)=>{
        console.log(result);
        res.render('list.ejs', {posts : result});
    });
});
 
 
module.exports = router;
 
 
cs

 

<reference>
https://stackoverflow.com/questions/24621940/how-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module

 

How to properly reuse connection to Mongodb across NodeJs application and modules

I've been reading and reading and still am confused on what is the best way to share the same database (MongoDb) connection across whole NodeJs app. As I understand connection should be open when app

stackoverflow.com

 

반응형
반응형

Node.js에서 python 스크립트를 실행하는 방법은 내장 모듈인 'child_process'의 spawn을 사용하면 된다.

먼저 실행할 python 코드를 작성하자.

1. python 스크립트 실행

"Hello World!"를 출력하는 python 스크립트

<hello.py>

1
print('Hello World!')
cs

 

2. 매개변수가 있는 python 함수 호출하기

func함수에 전달된 인자를 하나씩 출력한다.

<function.py>

1
2
3
4
5
6
7
8
9
import sys
 
def func(*args):
    for arg in args:
        print(arg)
 
 
if __name__=='__main__':
    func(*sys.argv[1:])
cs

 

 

node.js에서 전달한 인자는 sys.argv[1]부터 sys.argv[전달한 인자의 개수]에 저장된다.

python 스크립트가 인터프리터로 직접 실행되면 __name__이라는 글로벌 변수에 '__main__'이 할당된다.
그래서 python 스크립트 코드를 node.js에서 실행하게 되면 if문이 True 되어 func 함수가 호출된다.
.
이제 Node.js에서 python 코드를 실행해보자

<pythonCall.js>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const {spawn} = require('child_process');
let dataFromPyton;
 
/*python 코드 실행*/
const pythonProc1 = spawn('python', ['hello.py']);
pythonProc1.stdout.on('data', (data)=>{
    dataFromPyton = data.toString();
})
pythonProc1.on('close', (code)=>{
    console.log(dataFromPyton);
})
 
 
/*python 함수 인자 전달 실행*/
const pythonProc2 = spawn('python', ['function.py''arg1''arg2''arg3']);
pythonProc2.stdout.on('data', (data)=>{
    dataFromPyton = data.toString();
})
pythonProc2.on('close', (code)=>{
    console.log(dataFromPyton);
})
 
 
 
cs


spawn으로 python을 위한 자식 프로세스를 생성하고 이벤트 리스너를 등록한다.
python 스크립트가 호출되어 stdout에 print 한 결과가 전달되면 Node.js에서 그 결과를 콜백 함수로 전달한다.


[reference]
https://medium.com/swlh/run-python-script-from-node-js-and-send-data-to-browser-15677fcf199f

 

Run Python script from Node.js.

In this article i will go through a sample app that can run a python script from Node.js , get data from the script and send it to the…

medium.com


https://nodejs.org/api/child_process.html

 

Child process | Node.js v18.9.1 Documentation

Child process# Source Code: lib/child_process.js The node:child_process module provides the ability to spawn subprocesses in a manner that is similar, but not identical, to popen(3). This capability is primarily provided by the child_process.spawn() functi

nodejs.org

 

반응형

+ Recent posts