관리 메뉴

거니의 velog

231115_Node.js 개론 1 본문

대덕인재개발원/대덕인재개발원_파이썬 프로그래밍

231115_Node.js 개론 1

Unlimited00 2023. 11. 15. 08:26

* 자바스크립트는 원래 클라이언트 언어. 이제는 서버사이드 언어화 되면서 컨트롤러와 모델도 넘보기 시작했다.

* node.js의 부상. 

https://namu.wiki/w/Node.js?from=Nodejs

 

Node.js - 나무위키

Node.js로 프로그램을 개발하다 보면 여러 버전의 Node.js를 바꿔가며 사용해야 할 때가 있다. 이때마다 기존 버전을 삭제하고 다른 버전을 설치하는 작업을 매번 하기는 번거로우므로, 여러 개의

namu.wiki

* 버전 관리가 어려운 편


https://nodejs.org/en/download/

 

Download | Node.js

LTS Recommended For Most Users

nodejs.org


console.log("hello node");


var a = "1";
var b = 1;
var c = 1.1;
var d = true;
var e = false;

console.log(b + c); // 2.1
console.log(a + b); // 11
console.log(d && e); // false


var jumsu = 85;

var grade = "";
if(jumsu >= 90){
	grade = "수";
}else if(jumsu >= 80) {
	grade = "우";
}else if(jumsu >= 70) {
	grade = "미";
}else if(jumsu >= 60) {
	grade = "양";
}else{
	grade = "가";
}

console.log("당신의 점수는 " + grade + " 입니다.");


var sum = 0;
for(var i = 1; i <= 10; i++) {
	sum += i;
}

console.log(sum);


function showDan(dan) {
	console.log(dan + "*" + 1 + "=" + (dan*1));
	console.log(dan + "*" + 2 + "=" + (dan*2));
	console.log(dan + "*" + 3 + "=" + (dan*3));
	console.log(dan + "*" + 4 + "=" + (dan*4));
	console.log(dan + "*" + 5 + "=" + (dan*5));
	console.log(dan + "*" + 6 + "=" + (dan*6));
	console.log(dan + "*" + 7 + "=" + (dan*7));
	console.log(dan + "*" + 8 + "=" + (dan*8));
	console.log(dan + "*" + 9 + "=" + (dan*9));
	console.log("=========================================");
	for(var i = 1; i <= 9; i++){
		console.log(dan + "*" + i + "=" + (dan*i));
	}
}

showDan(5);


class Animal {
	constructor(full){
		this.full = full; // 전역 변수
	}
	eat(amount){
		this.full += amount;
	}
}

const dog = new Animal(0);
const cat = new Animal(0);

console.log("dog.full : " + dog.full);
dog.eat(10);
console.log("dog.full : " + dog.full);

console.log("cat.full : " + cat.full);
cat.eat(5);
console.log("cat.full : " + cat.full);


https://stackoverflow.com/questions/32657516/how-to-properly-export-an-es6-class-in-node-4

 

How to properly export an ES6 class in Node 4?

I defined a class in a module: "use strict"; var AspectTypeModule = function() {}; module.exports = AspectTypeModule; var AspectType = class AspectType { // ... }; module.export.AspectT...

stackoverflow.com

[animal.js]

class Animal {
	constructor(full){
		this.full = full; // 전역 변수
	}
	eat(amount){
		this.full += amount;
	}
}

const dog = new Animal(0);
const cat = new Animal(0);

/*console.log("dog.full : " + dog.full);
dog.eat(10);
console.log("dog.full : " + dog.full);

console.log("cat.full : " + cat.full);
cat.eat(5);
console.log("cat.full : " + cat.full);*/

module.exports = Animal;

[ooptest.js]

const Animal = require('./animal');

var ani = new Animal(0);
console.log("ani.full : " + ani.full);
ani.eat(10);
console.log("ani.full : " + ani.full);


[animal.js]

class Animal {
	constructor(full){
		this.full = full; // 전역 변수
	}
	eat(amount){
		this.full += amount;
	}
}

const dog = new Animal(0);
const cat = new Animal(0);

/*console.log("dog.full : " + dog.full);
dog.eat(10);
console.log("dog.full : " + dog.full);

console.log("cat.full : " + cat.full);
cat.eat(5);
console.log("cat.full : " + cat.full);*/

module.exports = Animal;

if (require.main === module) {
	var ani = new Animal(0);
	console.log("main에서 테스트한 ani.full : " + ani.full);
	ani.eat(10);
	console.log("main에서 테스트한 ani.full : " + ani.full);
}

[ooptest.js]

const Animal = require('./animal');

var ani = new Animal(0);
console.log("ani.full : " + ani.full);
ani.eat(10);
console.log("ani.full : " + ani.full);


[human.js]

const Animal = require('./animal');

class Human extends Animal {
	constructor(full){
		super(full);
		this.flag_tool = false;
	}
	momstouch(){
		this.flag_tool = true;
	}
}

module.exports = Human;

if (require.main === module) {
	var hum = new Human(0);
	console.log("hum.full : " + hum.full);
	console.log("hum.flag_tool : " + hum.flag_tool);
	hum.eat(10);
	hum.momstouch();
	console.log("hum.full : " + hum.full);
	console.log("hum.flag_tool : " + hum.flag_tool);
}

[ooptest.js]

const Animal = require('./animal');
const Human = require('./human');

/*var ani = new Animal(0);
console.log("ani.full : " + ani.full);
ani.eat(10);
console.log("ani.full : " + ani.full);*/

var hum = new Human(0);
console.log("hum.full : " + hum.full);
console.log("hum.flag_tool : " + hum.flag_tool);
hum.eat(10);
hum.momstouch();
console.log("hum.full : " + hum.full);
console.log("hum.flag_tool : " + hum.flag_tool);


이 경로에 cmd > npm install pysql로 설치

[mysql_select.js]

var mysql = require('mysql');

var conn = {
	host : 'localhost',
	port : '3305',
	user : 'root',
	password : 'python',
	database : 'python'
};

var connection = mysql.createConnection(conn); // DB 커넥션 생성
connection.connect(); // DB 접속

var sql = "select * from emp";

connection.query(sql, function(error, results, fields){
	if (error) {
		console.log(error);
	}
	console.log(error);
	console.log(results); // 이것만 사용할 것
	console.log(fields);
});

connection.end(); // DB 접속 종료

C:\workspace_python\.metadata\.plugins\org.eclipse.wildwebdeveloper.embedder.node\node-v16.13.0-win-x64\node.exe mysql_select.js 
null
[
  RowDataPacket { e_id: 1, e_name: '1', gen: '1', addr: '1' },
  RowDataPacket { e_id: 2, e_name: '2', gen: '2', addr: '2' },
  RowDataPacket { e_id: 3, e_name: '3', gen: '3', addr: '3' },
  RowDataPacket { e_id: 4, e_name: '4', gen: '4', addr: '4' },
  RowDataPacket { e_id: 5, e_name: '5', gen: '5', addr: '5' },
  RowDataPacket { e_id: 6, e_name: '6', gen: '6', addr: '6' },
  RowDataPacket { e_id: 7, e_name: '7', gen: '7', addr: '7' }
]
[
  FieldPacket {
    catalog: 'def',
    db: 'python',
    table: 'emp',
    orgTable: 'emp',
    name: 'e_id',
    orgName: 'e_id',
    charsetNr: 63,
    length: 11,
    type: 3,
    flags: 20483,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true
  },
  FieldPacket {
    catalog: 'def',
    db: 'python',
    table: 'emp',
    orgTable: 'emp',
    name: 'e_name',
    orgName: 'e_name',
    charsetNr: 33,
    length: 150,
    type: 253,
    flags: 0,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true
  },
  FieldPacket {
    catalog: 'def',
    db: 'python',
    table: 'emp',
    orgTable: 'emp',
    name: 'gen',
    orgName: 'gen',
    charsetNr: 33,
    length: 3,
    type: 253,
    flags: 0,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true
  },
  FieldPacket {
    catalog: 'def',
    db: 'python',
    table: 'emp',
    orgTable: 'emp',
    name: 'addr',
    orgName: 'addr',
    charsetNr: 33,
    length: 1200,
    type: 253,
    flags: 0,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true
  }
]

[mysql_insert.js]

var mysql = require('mysql');

var conn = {
	host : 'localhost',
	port : '3305',
	user : 'root',
	password : 'python',
	database : 'python'
};

var connection = mysql.createConnection(conn); // DB 커넥션 생성
connection.connect(); // DB 접속

console.log("start");

var e_id = "8";
var e_name = "8";
var gen = "8";
var addr = "8";
var sql = `
	INSERT INTO emp (e_id, e_name, gen, addr) 
	VALUES ('${e_id}', '${e_name}', '${gen}', '${addr}')
`;

connection.query(sql, function(error, results){
	if (error) {
		console.log(error);
	}
	console.log(results);
	console.log("results.affectedRows : " + results.affectedRows);
	console.log("results");
});

connection.end(); // DB 접속 종료
console.log("end");
C:\workspace_python\.metadata\.plugins\org.eclipse.wildwebdeveloper.embedder.node\node-v16.13.0-win-x64\node.exe mysql_insert.js 
start
end
OkPacket {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  serverStatus: 2,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0
}
results.affectedRows : 1
results // 비동기식(async)로 동작함을 알 수 있다.


[mysql_update.js]

var mysql = require('mysql');

var conn = {
	host : 'localhost',
	port : '3305',
	user : 'root',
	password : 'python',
	database : 'python'
};

var connection = mysql.createConnection(conn); // DB 커넥션 생성
connection.connect(); // DB 접속

var e_id = "8";
var e_name = "8888";
var gen = "8";
var addr = "8888888";
var sql = `
	UPDATE emp SET 
           e_name = '${e_name}'
           , gen = '${gen}'
           , addr = '${addr}'
     WHERE e_id = '${e_id}'
`;

connection.query(sql, function(error, results, fields){
	if (error) {
		console.log(error);
	}
	console.log("results.affectedRows : " + results.affectedRows);
});

connection.end(); // DB 접속 종료
results.affectedRows : 1


[mysql_delete.js]

var mysql = require('mysql');

var conn = {
	host : 'localhost',
	port : '3305',
	user : 'root',
	password : 'python',
	database : 'python'
};

var connection = mysql.createConnection(conn); // DB 커넥션 생성
connection.connect(); // DB 접속

var e_id = "8";
var sql = `
	DELETE FROM emp 
     WHERE e_id = '${e_id}'
`;

connection.query(sql, function(error, results, fields){
	if (error) {
		console.log(error);
	}
	console.log("results.affectedRows : " + results.affectedRows);
});

connection.end(); // DB 접속 종료
results.affectedRows : 1


f5를 누르면 생긴다.

[package.json]

{
  "dependencies": {
    "mysql": "^2.18.1",
    "sync-mysql": "^3.0.1"
  }
}

node_modules를 지워도 npm update를 치면 package.json에 있는 버전으로 다시 설치한다. 주변의 모듈까지 자동으로 설치

[package-lock.json]

{
  "name": "HELLO_NODE",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "dependencies": {
        "mysql": "^2.18.1"
      }
    },
    "node_modules/bignumber.js": {
      "version": "9.0.0",
      "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz",
      "integrity": "sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A==",
      "engines": {
        "node": "*"
      }
    },
    "node_modules/core-util-is": {
      "version": "1.0.3",
      "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
      "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="
    },
    "node_modules/inherits": {
      "version": "2.0.4",
      "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
      "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
    },
    "node_modules/isarray": {
      "version": "1.0.0",
      "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
      "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="
    },
    "node_modules/mysql": {
      "version": "2.18.1",
      "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.18.1.tgz",
      "integrity": "sha512-Bca+gk2YWmqp2Uf6k5NFEurwY/0td0cpebAucFpY/3jhrwrVGuxU2uQFCHjU19SJfje0yQvi+rVWdq78hR5lig==",
      "dependencies": {
        "bignumber.js": "9.0.0",
        "readable-stream": "2.3.7",
        "safe-buffer": "5.1.2",
        "sqlstring": "2.3.1"
      },
      "engines": {
        "node": ">= 0.6"
      }
    },
    "node_modules/process-nextick-args": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
      "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
    },
    "node_modules/readable-stream": {
      "version": "2.3.7",
      "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz",
      "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==",
      "dependencies": {
        "core-util-is": "~1.0.0",
        "inherits": "~2.0.3",
        "isarray": "~1.0.0",
        "process-nextick-args": "~2.0.0",
        "safe-buffer": "~5.1.1",
        "string_decoder": "~1.1.1",
        "util-deprecate": "~1.0.1"
      }
    },
    "node_modules/safe-buffer": {
      "version": "5.1.2",
      "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
      "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
    },
    "node_modules/sqlstring": {
      "version": "2.3.1",
      "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz",
      "integrity": "sha512-ooAzh/7dxIG5+uDik1z/Rd1vli0+38izZhGzSa34FwR7IbelPWCCKSNIl8jlL/F7ERvy8CB2jNeM1E9i9mXMAQ==",
      "engines": {
        "node": ">= 0.6"
      }
    },
    "node_modules/string_decoder": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
      "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
      "dependencies": {
        "safe-buffer": "~5.1.0"
      }
    },
    "node_modules/util-deprecate": {
      "version": "1.0.2",
      "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
      "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
    }
  }
}

* package-lock.json, package.json 은 꼭 챙겨야 할 필요가 있다. maven처럼 버전 관리를 할 수 있다.

* npm update 명령어도 기억할 것!


https://hanswsw.tistory.com/3

 

[Node.js] mysql을 쉽게 동기식으로 사용해보자! (sync-mysql)

요번 포스팅에서는,Node.js에서 mysql을 사용하는 경우, 아주 간단한 방법으로 mysql의 쿼리를 동기식으로 처리할 수 있는 모듈을 소개해드리고자 합니다. 이전 포스팅에서 언급했듯이, node.js에서 함

hanswsw.tistory.com

npm install sync-mysql

[package.json]

{
  "dependencies": {
    "mysql": "^2.18.1",
    "sync-mysql": "^3.0.1"
  }
}

[syc_select.js]

// mysql이 동기식으로 움직이는 것이 딱 하나 있음.
// mysql syc로 검색

var mysql = require('sync-mysql');

var conn = {
	host : 'localhost',
	port : '3305',
	user : 'root',
	password : 'python',
	database : 'python'
};

var connection = new mysql(conn); // DB 커넥션 생성

var sql = `
	select * 
	  from emp
`;

var result = connection.query(sql);
console.log(result);

connection.dispose();
[
  { e_id: 1, e_name: '1', gen: '1', addr: '1' },
  { e_id: 2, e_name: '2', gen: '2', addr: '2' },
  { e_id: 3, e_name: '3', gen: '3', addr: '3' },
  { e_id: 4, e_name: '4', gen: '4', addr: '4' },
  { e_id: 5, e_name: '5', gen: '5', addr: '5' },
  { e_id: 6, e_name: '6', gen: '6', addr: '6' },
  { e_id: 7, e_name: '7', gen: '7', addr: '7' }
]

https://github.com/ForbesLindesay/sync-mysql

 

GitHub - ForbesLindesay/sync-mysql: Make synchronous queries to a mysql database

Make synchronous queries to a mysql database. Contribute to ForbesLindesay/sync-mysql development by creating an account on GitHub.

github.com

[syc_insert.js]

// mysql이 동기식으로 움직이는 것이 딱 하나 있음.
// mysql syc로 검색

var mysql = require('sync-mysql');

var conn = {
	host : 'localhost',
	port : '3305',
	user : 'root',
	password : 'python',
	database : 'python'
};

var connection = new mysql(conn); // DB 커넥션 생성

var e_id = "8";
var e_name = "8";
var gen = "8";
var addr = "8";

var sql = `
	INSERT INTO emp (e_id, e_name, gen, addr) 
	VALUES ('${e_id}', '${e_name}', '${gen}', '${addr}')
`;

var result = connection.query(sql);
console.log("result.affectedRows : " + result.affectedRows);

connection.dispose();
result.affectedRows : 1


[syc_update.js]

// mysql이 동기식으로 움직이는 것이 딱 하나 있음.
// mysql syc로 검색

var mysql = require('sync-mysql');

var conn = {
	host : 'localhost',
	port : '3305',
	user : 'root',
	password : 'python',
	database : 'python'
};

var connection = new mysql(conn); // DB 커넥션 생성

var e_id = "8";
var e_name = "8888";
var gen = "8";
var addr = "8888888";

var sql = `
	UPDATE emp SET 
           e_name = '${e_name}'
           , gen = '${gen}'
           , addr = '${addr}'
     WHERE e_id = '${e_id}'
`;

var result = connection.query(sql);
console.log("result.affectedRows : " + result.affectedRows);

connection.dispose();
result.affectedRows : 1


[syc_delete.js]

// mysql이 동기식으로 움직이는 것이 딱 하나 있음.
// mysql syc로 검색

var mysql = require('sync-mysql');

var conn = {
	host : 'localhost',
	port : '3305',
	user : 'root',
	password : 'python',
	database : 'python'
};

var connection = new mysql(conn); // DB 커넥션 생성

var e_id = "8";

var sql = `
	DELETE FROM emp 
     WHERE e_id = '${e_id}'
`;

var result = connection.query(sql);
console.log("result.affectedRows : " + result.affectedRows);

connection.dispose();
result.affectedRows : 1


[cmd C:\Windows\System32\cmd.exe]

npm install express

[package.json]

{
  "dependencies": {
    "express": "^4.18.2",
    "mysql": "^2.18.1",
    "sync-mysql": "^3.0.1"
  }
}

[my_express.js]

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
	res.send('Hello Express!')
});

app.listen(port, () => {
	console.log(`Example app listening on port ${port}`)
});

- http://localhost:3000/


const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
	res.send('Hello Express!');
});

app.get('/param', (req, res) => {
	var menu = req.query.menu;
	res.send('PARAM : ' + menu);
});

app.listen(port, () => {
	console.log(`Example app listening on port ${port}`);
});

- http://localhost:3000/param?menu=%EC%A7%AC%EB%BD%95


 

'대덕인재개발원 > 대덕인재개발원_파이썬 프로그래밍' 카테고리의 다른 글

00_기타 자료실  (0) 2023.11.16
231116_Node.js 개론 2  (0) 2023.11.16
231114_Django 개론 5  (0) 2023.11.14
231113_Django 개론 4  (0) 2023.11.13
231110_Django 개론 3  (0) 2023.11.10