var fs = require('fs');
console.log('A');
fs.readFile('syntax/sample.txt', 'utf8', function(err, result){
console.log(result);
});
console.log('C');
결과값 ABC
var fs = require('fs');
console.log('A');
var result = fs.readFileSync('syntax/sample.txt', 'utf8');
console.log(result);
console.log('C');
결과값 ACB
함수명 + Sync
이다.실행되고 있는 프로그램을 관리해주는 Node.js 툴이다. 우리가 디버깅을 할 때 계속 node main.js + ctrl+c 를 입력했다. PM2는 이러한 부분을 보다 관리하기 쉽게 도와준다.
function templateHTML(title, list, body){
~~~
<a href="/create">create</a>
~~~
}
else if(pathname === '/create'){
fs.readdir('./data', function(error, filelist){
var title = 'WEB - create';
var list = templateList(filelist);
var template = templateHTML(title, list, `
<form action="http://localhost:3000/process_create" method="post">
<p><input type="text" name="title" placeholder="title"></p>
<p>
<textarea name="description" placeholder="description"></textarea>
</p>
<p>
<input type="submit">
</p>
</form>
`);
response.writeHead(200);
response.end(template);
});
var app = http.createServer(function(request,response){
~~~
// 쿼리 스트링 선언
var qs = require('querystring');
~~~
else if(pathname === '/create_process'){
var body = '';
// 서버에서 데이터를 조금씩 읽어올때마다 콜백함수 실행
// 데이터 수신
request.on('data', function(data){
body = body + data;
});
// 정보 수신이 끝나면 실행
request.on('end', function(){
var post = qs.parse(body);
var title = post.title;
var description = post.description
});
response.writeHead(200);
response.end('success');
}
else if(pathname === '/create_process'){
var body = '';
request.on('data', function(data){
body = body + data;
});
request.on('end', function(){
var post = qs.parse(body);
var title = post.title;
var description = post.description;
// 저장 경로 / 문서 이름, 저장할 문서 내용, 형식
fs.writeFile(`data/${title}`, description, 'utf8', function(err){
response.writeHead(302, {Location: `/?id=${title}`});
response.end();
})
});
}
writeFile
: 데이터를 받아 파일을 생성/?id=${title}
});302
: 해당 Location으로 이동 (리다이렉션) //매개변수 control 추가
function templateHTML(title, list, body, control){
return `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
// control 생성
${control}
${body}
</body>
</html>
`;
}
~~~
fs.readdir('./data', function(error, filelist){
var title = 'Welcome';
var description = 'Hello, Node.js';
var list = templateList(filelist);
var template = templateHTML(title, list,
`<h2>${title}</h2>${description}`,
// control 매개변수 값 (create 링크만 있음)
`<a href="/create">create</a>`
);
response.writeHead(200);
response.end(template);
});
} else {
fs.readdir('./data', function(error, filelist){
fs.readFile(`data/${queryData.id}`, 'utf-8', function(err, description){
var title = queryData.id;
var list = templateList(filelist);
var template = templateHTML(title, list,
`<h2>${title}</h2>${description}`,
// control 매개변수 값 (create, update 링크 둘다 있음)
`<a href="/create">create</a >
<a href="/update?id=${title}">update</a>`
);
response.writeHead(200);
response.end(template);
});
});
~~~
// update의 경로로 접속시 조건문
else if(pathname === '/update'){
fs.readdir('./data', function(error, filelist){
fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description){
var title = queryData.id;
var list = templateList(filelist);
var template = templateHTML(title, list,
`
<form action="/update_process" method="post">
// input type을 hidden으로 설정하여 사용자에게 보이지 않게 한다.
// value를 title로 만들어 초기 입력값을 기존 값으로 설정한다.
<input type="hidden" name="id" value="${title}">
// 이 부분도 value를 title로 두어 기존에 저장되어 있던 값을 불러온다.
<p><input type="text" name="title" placeholder="title" value="${title}"></p>
<p>
// textarea는 input과 다르게 value가 없다 그래서 태그 사이에 값을 입력해준다.
<textarea name="description" placeholder="description">${description}</textarea>
</p>
<p>
<input type="submit">
</p>
</form>
`,
`<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
);
~~~
// url주소가 /update_process인 경우
else if (pathname === '/update_process') {
var body = '';
request.on('data', function(data){
body = body + data;
});
request.on('end', function(){
var post = qs.parse(body);
var id = post.id;
var title = post.title;
var description = post.description;
// 기존 파일 명, 바꿀 파일 명
fs.rename(`data/${id}` , `data/${title}` ,function(err) {
// 기존 코드 재활용
fs.writeFile(`data/${title}`, description , `utf-8` , function (err) {
response.writeHead(302, {Location : `/?id=${title}`});
response.end('success');
});
})
console.log(post);
});
}
fs.readdir('./data', function(error, filelist){
fs.readFile(`data/${queryData.id}`, 'utf-8', function(err, description){
var title = queryData.id;
var list = templateList(filelist);
var template = templateHTML(title, list,
`<h2>${title}</h2>${description}`,
`<a href="/create">create</a > <a href="/update?id=${title}">update</a>
// templateHTML함수에 delete 폼 추가
<form action="delete_process" method="post">
<input type="hidden" name="id" value="${title}">
<input type="submit" value="delete">
</form>`
);
response.writeHead(200);
response.end(template);
});
});
// delete_process에 접근하는 경우
else if (pathname === '/delete_process') {
var body = '';
request.on('data', function(data){
body = body + data;
});
request.on('end', function(){
var post = qs.parse(body);
var id = post.id;
// 삭제할 파일 경로 , 콜백 함수
fs.unlink(`data/${id}`, function() {
// 파일 삭제 후 홈으로 이동
response.writeHead(302, {Location : '/'});
response.end();
})
});
}