<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alvin on Medium]]></title>
        <description><![CDATA[Stories by Alvin on Medium]]></description>
        <link>https://medium.com/@HoseungJang?source=rss-b4176643244d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rt5RkMhOLxdp7ffb-Srxhw.jpeg</url>
            <title>Stories by Alvin on Medium</title>
            <link>https://medium.com/@HoseungJang?source=rss-b4176643244d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:04:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@HoseungJang/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Video Streaming with Node.js / HLS]]></title>
            <link>https://medium.com/@HoseungJang/video-streaming-with-node-js-9401213a04e7?source=rss-b4176643244d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9401213a04e7</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[http-live-streaming]]></category>
            <category><![CDATA[hls-server]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[hls]]></category>
            <dc:creator><![CDATA[Alvin]]></dc:creator>
            <pubDate>Wed, 27 May 2020 02:55:02 GMT</pubDate>
            <atom:updated>2020-09-14T17:50:13.371Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I’m not good at English. If there is something wrong in this story, please give me a feedback at hsjang.dev@gmail.com.</blockquote><p>Video is one of the representative resources that server provides. But video is also one of the difficult resources to provide.</p><p>There are 2 ways to get resources from a server. The first way is to download the entire resource. And the second way is to segment the resource into small pieces and get them in real-time.</p><p>First of all, to get video with the first way is inappropriate. Because video has large size. In addition, users may not watch video to the end, and a server should consider quality of video depending on user’s network condition.</p><p>Therefore, I will share my experience that sending video with the second way using HTTP Live Streaming.</p><h3>Advantages of HLS</h3><ul><li>Because HLS based on HTTP, You can save more cost than other way.</li><li>You can utilize advantages of HTTP like caching.</li></ul><h3>So What is HLS?</h3><p>HTTP Live Streaming(HLS) is HTTP-based streaming protocol.</p><p>HLS uses .m3u8 and .ts files.</p><ul><li>.m3u8: A file that has information list of segmented videos</li><li>.ts: A file for each segmented video</li></ul><p>Process of HLS is:</p><ol><li>A client requests .m3u8 file to a server.</li><li>A server responds .m3u8 file to a client.</li><li>A client reads .m3u8 file and requests .ts files in order.</li><li>A server responds .ts files to a client.</li></ol><p>HTTP has only one response to one request. So a client requests .ts files in due course to keep video playing.</p><h3>Prepare to develop</h3><ol><li>Prepare a moderate-length video. This story use .mp4 format.</li><li>Install Node.js.</li><li>Please enter command below to install frameworks &amp; modules.</li></ol><pre>npm install express<br>npm install fluent-ffmpeg @ffmpeg-installer/ffmpeg<br>npm install hls-server</pre><p>4. Organize directory as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*pZ2np0i9j2rPLypLyMGu6Q.png" /></figure><h3>Generate .m3u8 and .ts files</h3><p>Write ffmpeg.js as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*IpPmQ7S49uWf6EsxNWqCJQ.png" /></figure><p>The code above generates .m3u8 and .ts files.<br>The most important options that .addOptions method get is:</p><ul><li>-hls_time: Set length of segmented video in seconds.</li><li>-f: Set the format. Of course it should be ‘hls’.</li></ul><p>ffmpegInstaller is resolver of the error that occur when you only use ffmpeg.</p><p>Run ffmpeg.js when you’re done to write. And terminate it when “end” is logged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*InwxO6rh0x1I2QfVxgmaFA.png" /></figure><p>Then you can see .m3u8 and .ts files are generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*eGOfNIE3xXZwyBADI9fDNw.png" /></figure><p>The picture above is contents of output.m3u8. .ts files are recorded sequentially. A client requests to a server based on this contents.</p><h3>Write HTML</h3><p>Write client.html as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*aGdc0YS0bBBfFn-PRMYUUg.png" /></figure><p>In the above code, you should focus on javascript code. You can see the code imports hls.js and use. hls.js makes video player that is enable to use HLS.</p><p>Next step is preparing a server.</p><h3>Write server code</h3><p>Write express router as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*oCHSXixw-uL9wiXdmlQmjw.png" /></figure><p>To use the stream, fs is required. And this router responds client.html to a client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*z4Q-VAlQWHJLUYAdRvuxUQ.png" /></figure><p>The code above makes be able to stream video with HLS. Descriptions of properties of provider are:</p><ul><li>exists: A function that is ran on all requests. It check a file exists. If you passed null and true to cb, It means a file exists and ready to stream. But if you passed null and false to cb, It means a file not exists.</li><li>getMainfestStream: A function that is ran on requests for .m3u8 file. Pass null and stream to cb.</li><li>getMainfestStream: A function that is ran on requests for .ts file. Pass null and stream to cb.</li></ul><p>if you want to learn more about hls-server, go to <a href="https://www.npmjs.com/package/hls-server">here</a>.<br>I uploaded this examples on my <a href="https://github.com/HoseungJang/express-hls-example">github</a>.</p><h3>Output</h3><p>Now you ready to stream video with HLS. Run server and go to localhost:3000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*R8VtVyAWcAhVqaVqqNjUHQ.png" /></figure><p>Then you can see video player.(I love singing.) Press F12 key and go to Network tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*nqaHuHjq5lOfMPhGrLUdHQ.png" /></figure><p>You can see a client got .m3u8 file and part of .ts files in advance to keep video playing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*SR1uiBSTEojKPy5V3nwUnw.png" /></figure><p>While you’re watching video, a client requests .ts files continually.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9401213a04e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript에서 async/await의 병목 문제 개선하기]]></title>
            <link>https://medium.com/@HoseungJang/javascript%EC%97%90%EC%84%9C-async-await%EC%9D%98-%EB%B3%91%EB%AA%A9-%EB%AC%B8%EC%A0%9C-%EA%B0%9C%EC%84%A0%ED%95%98%EA%B8%B0-60d54795c4fa?source=rss-b4176643244d------2</link>
            <guid isPermaLink="false">https://medium.com/p/60d54795c4fa</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[병목]]></category>
            <category><![CDATA[비동기]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Alvin]]></dc:creator>
            <pubDate>Sun, 17 May 2020 09:07:21 GMT</pubDate>
            <atom:updated>2020-05-17T09:09:14.558Z</atom:updated>
            <content:encoded><![CDATA[<h3>개요</h3><p>Javascript의 async/await는 비동기 처리를 콜백의 맞물림 없이 깔끔하게 처리할 수 있도록 도와주는 문법입니다. 동일한 역할을 하는 Promise보다 코드가 깔끔해지고, 직관적이기에 저는 Promise보다 async/await를 선호합니다.</p><p>하지만 async/await를 남용하면 느리지 않아도 될 작업을 느리게 만들 수 있습니다. 이번 글에서는 async/await를 남용했을 때 생기는 병목 현상을 개선해보겠습니다.</p><h3>첫 번째 예시</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*ZlIDi_zOGZzgSPUuiqaCMw.png" /></figure><p>Promise를 반환하는 async 함수 a, b, c를 선언했습니다. 각각의 Promise는 1초 후 resolve 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*jSSJzkdgM9eQp0tDlAjTCw.png" /></figure><p>함수 a, b, c를 실행하는 main 함수입니다. console.time(), console.timeEnd()는 main 함수의 실행시간을 측정하기 위해서 작성하였습니다. 이제 위처럼 await를 단순 나열하는 것이 어떤 결과를 불러일으키는지 확인해봅시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*c39f514WQF24HUZPi1Xe0Q.png" /></figure><p>위는 실행 결과를 캡쳐한 사진입니다. 분명히 함수 a, b, c가 return하는 각각의 Promise들은 1초 후 resolve되고, async/await는 비동기 처리 문법이라고 했습니다. 그런데 모든 Promise가 resolve되고 main이 종료되기까지 무려 3초의 시간이 걸렸습니다. 어째서일까요?</p><p>그 이유는 바로 async/await는 코드가 동기적으로 실행되도록 만들기 때문입니다. 따라서 실행 시간이 불규칙적인 비동기 작업을 개발자가 의도한 순서대로 동작시킬 수 있는 것입니다. 하지만 잘못 사용했더니 ‘직관성’은 얻었지만 ‘속도’를 잃었습니다.</p><p>그러나 아직 슬퍼하기엔 이릅니다. 우리에겐 Promise.all이라는 친구가 있습니다.</p><h3>Promise.all</h3><p>Promise.all은 인자로 Promise 배열을 받고, 병렬로 처리합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*_LagEXmacoRc8XC4OefC-Q.png" /></figure><p>main 함수를 수정했습니다. await를 단순 나열하는 것 대신 Promise.all을 사용하도록 하였습니다. 아래는 그 결과입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*v3qejnMeq-ozftlWgg1VoQ.png" /></figure><p>위에서 봤던 결과와 다르게 main 함수가 1초만에 종료되었습니다. 각각의 Promise가 병렬로 처리되었기 때문입니다. 함수 a, b, c의 Promise가 서로 의존적이었다면 Promise.all을 사용하면 안되지만, 서로 독립적이었기 때문에 병렬로 처리해서 실행 시간을 단축할 수 있었습니다.</p><p>이제 async/await의 모든 병목을 해결할 수 있을까요? 아닙니다. 또 다른 예시를 살펴봅시다.</p><h3>두 번째 예시</h3><p>위에서 작성한 함수 a, b, c를 수정해줍시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Iyk8DHDFqawzpo8cTmkwSg.png" /></figure><p>함수 a의 Promise는 2초 후 resolve됩니다. 함수 b의 Promise는 1.5초 후 resolve되고 결과값으로 1000을 넘깁니다. 함수 c의 Promise는 n초 후 resolve됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*FLVSqwIPhqQJ1ygE1Gc2xg.png" /></figure><p>main 함수도 수정해줍시다. 함수 a, b의 Promise는 동시에 실행됩니다. 그리고 b의 결과를 받아서 c를 실행합니다. 함수 b의 Promise의 결과가 1000이므로, 함수 c의 Promise는 1초 후 resolve됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*uCQmLsjvG6uBiOquxg-i0w.png" /></figure><p>실행 결과입니다. 3초가 걸렸지만, 더 빠르게 끝낼 수도 있습니다. main 함수를 자세히 살펴봅시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*Apb7WnGXdd5A2e1qWFW19w.png" /></figure><p>함수 a의 Promise는 2초 후 resolve됩니다. 그러나 함수 b의 Promise는 1.5초 후 resolve 되기 때문에 a의 Promise가 끝날 때 까지 기다리게 됩니다. 그 후 c가 실행되고, 1초 후에 resolve되어 총 실행시간이 3초가 되는 것입니다.</p><p>위 코드의 문제점은 c는 b의 결과를 받지만, a가 끝날때 까지 기다린다는 것입니다. 이런 경우 b와 c를 먼저 처리해줌으로써 실행시간을 단축할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*KrcupbrfCiG-wtljpbZUbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*nt9OwbJZISnTEkS7BuebMg.png" /></figure><p>수정한 main 함수와 그 결과입니다. a의 Promise보다 b의 Promise를 먼저 await함으로써 c를 빨리 처리할 수 있게 되었고, 실행시간이 단축되었습니다.</p><h3>마무리</h3><p>이번 글에서는 async/await의 병목 현상을 알아보고, 개선해보았습니다. 사실 저도 얼마전까진 async/await의 병목에 대해서 몰랐습니다. 아니, 몰랐던 것이 아니라 어차피 하드웨어의 성능이 좋아 충분히 빠르다는 안일한 핑계로 문제를 외면했을 지도 모르겠습니다.</p><p>하지만 최근에 <a href="https://medium.com/@sijk0331/aws-cloudfront%EB%A1%9C-%EC%84%9C%EB%B2%84-%EC%9D%91%EB%8B%B5-%EC%86%8D%EB%8F%84-%EA%B0%9C%EC%84%A0%EC%8B%9C%ED%82%A4%EA%B8%B0-6960d0776dc5">CloudFront로 캐싱 서버를 구축</a>하면서, 아무리 짧은 시간의 지연이라도 사용자 경험을 크게 해칠 수 있다는 것을 깨달았습니다. 그래서 이 글을 작성하게 되었고, 짧은 코드 한줄이라도 얼마나 신중하게 작성해야 하는지 깨달은 것 같습니다.</p><p>최고의 사용자 경험을 위해선 클라이언트의 역할도 중요하겠지만, 컨텐츠를 빠르고 안정적으로 응답하는 서버의 역할도 매우 중요할 것입니다. 그런 의미에서 서버 개발자인 제가 기본을 소홀히 한 것 같아 반성하게된 하루였습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60d54795c4fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript의 Optional Chaining, Nullish Coalescing]]></title>
            <link>https://medium.com/@HoseungJang/typescript%EC%9D%98-optional-chaining-nullish-coalescing-bf65eb9af3d7?source=rss-b4176643244d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf65eb9af3d7</guid>
            <category><![CDATA[optional-chaining]]></category>
            <category><![CDATA[nullish-coalescing]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[타입스크립트]]></category>
            <dc:creator><![CDATA[Alvin]]></dc:creator>
            <pubDate>Wed, 06 May 2020 15:43:07 GMT</pubDate>
            <atom:updated>2020-07-13T00:49:50.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*jFs_jiPZkS0pnzDc.png" /></figure><h3>개요</h3><p>JavaScript가 가진 양날의 검은 타입의 유연함일 것입니다. 개발은 편하고 빠르겠지만 유지보수가 끔찍해집니다. 그래서 개발자들은 TypeScript라는 훌륭한 기술을 만들어냈습니다. 타입에 관련된 에러가 확실히 줄어서 기쁩니다. 그런데..? null과 undefined가 여전히 개발자를 괴롭힙니다.</p><p>이번 글에서는 TypeScript 3.7부터 지원하는 Optional Chaining과 Nullish Coalescing을 알아보고, null, undefined가 만드는 문제를 개선하는 방법에 대해서 공유하려고 합니다.</p><h3>Optional Chaining</h3><p>Optional Chaining은 체이닝에서 null 또는 undefined가 반환되면 다음 체이닝으로 넘어가지 않고 undefined를 반환합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*8AzkrfbMH60kT3CUvHQLwQ.png" /></figure><p>맥북을 사오는 코드를 작성해 봤습니다. 여기서 null(또는 undefined)의 프로퍼티를 읽지 말라는 에러가 나왔다고 가정해봅시다. 그렇다면 apple이 null 또는 undefined인지 검사하는 코드를 추가해서 해결할 수 있을 것입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*q8BqPjqP9PfU3eu4t64yRg.png" /></figure><p>위의 코드는 이해하기도 쉽고 의도한대로 동작합니다. 그런데 뭔가 뚱뚱합니다. 결과적으로 맘에 들지가 않습니다.(제일 심각한 문제군요) 그렇다면 3항 연산자 대신 Optional Chaining을 사용해 보겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*-gzAiWjxy0E_qVA7AhjpgA.png" /></figure><p>코드가 확실히 간결해진걸 볼 수 있습니다.(이제야 만족스럽네요) 간단히 ‘.’ 을 ‘?.’ 로 수정한 것 뿐인데 에러도 피하고 가독성까지 챙겼습니다. 와우.</p><h3>Nullish Coalescing</h3><p>Nullish Coalescing은 피연산자가 null 또는 undefined인지 검사합니다.</p><p>갑자기 인자값이 null 또는 undefined가 아닐 때만 그대로 출력하는 함수를 만들고 싶습니다. 이 때 아래와 같이 작성해볼 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*opzgN6avub9zO98nTv0VBw.png" /></figure><p>언뜻 보기에는 문제가 없어보입니다. null, undefined를 넣어보니 의도한대로 동작합니다. 그런데 echo 함수에 0, 빈 문자열, false 같이 false로 취급되는 값들을 넘기면 어떻게 될까요? null과 undefined가 아닌데도 “Cannot logging null or undefined”가 출력될 것입니다. 바로 이런 상황에 Nullish Coalescing을 사용하면 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*czuQQFTkr32Hw-KNFC3CBg.png" /></figure><p>Nullish Coalescing을 사용하는 방법은 간단합니다. ‘||’ 대신 ‘??’를 사용하면 됩니다. 이제야 echo 함수가 의도한대로 동작하네요.</p><h3>마무리</h3><p>TypeScript의 Optional Chaining, Nullish Coalescing 문법을 알아보았습니다. 사용하는 기술의 업데이트 내용을 확인하는 것이 얼마나 큰 도움이 되는지 느낄 수 있었습니다.</p><p>하지만 자칫하면 남용될 수 있습니다. 특히 Optional Chaining은 조심하지 않으면 또 다른 문제를 낳을 가능성이 보입니다.(체이닝의 반환값이 undefined인데 그대로 사용한다던가..)</p><p>새로운 기술을 적용하는 것도 좋지만 그만큼 신중해야 한다는 것도 기억해야할 것 같습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf65eb9af3d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js, Express, HLS로 동영상 스트리밍하기]]></title>
            <link>https://medium.com/@HoseungJang/node-js-express-hls%EB%A1%9C-%EB%8F%99%EC%98%81%EC%83%81-%EC%8A%A4%ED%8A%B8%EB%A6%AC%EB%B0%8D%ED%95%98%EA%B8%B0-46006408a0e6?source=rss-b4176643244d------2</link>
            <guid isPermaLink="false">https://medium.com/p/46006408a0e6</guid>
            <category><![CDATA[스트리밍]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[http-live-streaming]]></category>
            <category><![CDATA[hls]]></category>
            <category><![CDATA[동영상]]></category>
            <dc:creator><![CDATA[Alvin]]></dc:creator>
            <pubDate>Tue, 05 May 2020 15:11:01 GMT</pubDate>
            <atom:updated>2020-09-10T13:18:51.766Z</atom:updated>
            <content:encoded><![CDATA[<h3>개요</h3><p><strong>동영상</strong>은 서버가 제공하는 <strong>대표적인 자원</strong> 중 하나입니다. 그러나 동영상은 제공하기 <strong>까다로운</strong> 자원 중 하나이기도 합니다.</p><p>서버로부터 <strong>자원을 가져오는 방법</strong>은 크게 두 가지로 나눌 수 있을 것입니다. 첫 번째로 <strong>전체를 다운로드</strong> 하는 방법, 두 번째로 자원을 <strong>잘게 나눠서 실시간으로 전달</strong>하는 방법입니다. 우선 동영상은 첫 번째 방법으로 가져오기엔 무리가 있다고 보여집니다. 왜냐하면 기본적으로 용량이 큰 자원이기 때문입니다. 또한 사용자가 동영상을 <strong>끝까지 시청하지 않을 수도</strong> 있고, <strong>사용자의 네트워크 상태</strong>에 따라서 동영상의 품질도 고려해야할 것입니다.</p><p>따라서 실시간으로 동영상을 분할하여 전달하는 방법의 필요성을 느끼게 되었고, <strong>HLS</strong>를 사용해서 동영상 스트리밍을 실습해본 과정을 공유하려고 합니다.</p><h3>HLS의 장점</h3><ul><li>HTTP를 사용하기 때문에다른 프로토콜을 사용하는 방식보다 <strong>도입 비용을 절약</strong>할 수 있습니다.</li><li>캐싱같은 HTTP의 장점을 그대로 활용할 수 있습니다.</li></ul><h3>그래서 HLS란?</h3><p><strong>HLS</strong>는 <strong>HTTP Live Streaming</strong>의 약자입니다. 말그대로 HTTP 프로토콜을 사용하는 실시간 스트리밍 방식입니다.</p><p>HLS는 스트리밍에 .m3u8, .ts 형식의 파일을 사용합니다.</p><ul><li>.m3u8: 스트리밍할 동영상을 분할한 파일(.ts 파일)들의 정보가 순차적으로 저장되어있는 파일입니다.</li><li>.ts: 분할된 동영상 파일이라고 생각하시면 될 것 같습니다. (TypeScript 아닙니다.)</li></ul><p>스트리밍의 대략적인 흐름은 아래와 같습니다.</p><ol><li>클라이언트는 .m3u8 파일을 요청한다.</li><li>서버는 .m3u8 파일을 응답한다.</li><li>클라이언트는 .m3u8 파일을 읽고, 재생 시간에 맞춰서 .ts 파일을 순차적으로 요청한다.</li><li>서버는 .ts 파일을 응답한다.</li></ol><p>HTTP는 하나의 요청에 하나의 응답만 존재합니다. 따라서 클라이언트는 동영상 재생이 중단되지 않도록 적절한 때에 .ts 파일을 요청합니다.</p><p>HLS에 대해 더 자세한 설명이 필요하시다면 <a href="https://d2.naver.com/helloworld/7122">이곳</a>을 확인해주세요.</p><h3>개발 준비</h3><ol><li>적당한 길이의 동영상을 하나 준비해주세요. 이 글에서는 .mp4 형식의 동영상을 사용합니다.</li><li>Node.js를 설치해주세요.</li><li>그리고 아래의 명령어를 입력해서 프레임워크와 모듈을설치해줍시다.</li></ol><pre>npm install express<br>npm install fluent-ffmpeg @ffmpeg-installer/ffmpeg<br>npm install hls-server</pre><p>4. 디렉토리는 아래와 같이 구성해줍시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*CAohft3LznPam0Gj9QDRXw.png" /></figure><h3>.m3u8, .ts 파일 생성하기</h3><p>ffmpeg.js 파일을 아래와 같이 작성해줍시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*kp2LSmC02ps9BttzRQTszA.png" /></figure><p>video.mp4 파일로부터 .m3u8, .ts 파일을 생성하는 코드입니다. ffmpeg에게 넘긴 옵션 중 중요한 옵션들은 아래와 같습니다.</p><ul><li>-hls_time: 몇 초 단위로 동영상을 분할할 것인지 설정합니다. 저는 10초 단위로 분할하도록 설정했습니다.</li><li>-f: 포맷을 설정합니다. 당연히 hls로 설정했습니다.</li></ul><p>ffmpegInstaller 관련 코드는 <a href="https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/issues/748">ffmpeg만 사용했을 때 생겼던 오류를 해결</a>하기 위해서 작성했습니다.</p><p>다음은 ffmpeg.js 파일을 실행시킬 차례입니다. end가 출력되면 실행을 종료해줍시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*xouVVw0gIhRATzUkiQt6Dw.png" /></figure><p>.m3u8 파일과 .ts 파일들이 생성된 것을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*XdqfXuVGYG_m4v3lwpTDjg.png" /></figure><p>.m3u8 파일의 내부에는 .ts파일이 순차적으로 기록되어 있는 것을 볼 수 있습니다. 클라이언트는 이 내용을 기반으로 서버에 요청하게 됩니다.</p><h3>HTML 작성</h3><p>HLS를 위한 중요한 준비물을 챙겼으니 HTML을 작성해줍시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*dUMwXe3kkPRI4s949SHq8Q.png" /><figcaption>client.html</figcaption></figure><p>여기서 주목해야할 점은 자바스크립트 코드입니다. hls.js를 불러와서 사용하는 것을 볼 수 있습니다. hls.js는 HLS를 위한 비디오 플레이어를 만들어줍니다.</p><h3>서버 코드 작성</h3><p>.m3u8, .ts, 클라이언트까지 준비가 되었습니다. 이제는 서버를 준비할 차례입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*0AKzA8WtoJ1BLDrIQ8VXBQ.png" /><figcaption>app.js 1~8번째 줄</figcaption></figure><p>express, fs, hls-server를 가져왔습니다. fs는 stream를 생성하기 위해서 필요합니다. 그리고 HTML을 응답하는 라우터를 작성했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*lCXTI-CWWCFuUPUGIK-zSQ.png" /><figcaption>app.js 9~37번째 줄</figcaption></figure><p>HLS 서버 코드입니다. provider의 각 속성들에 대한 설명은 아래와 같습니다.</p><ul><li>exists: 모든 요청에 대해 실행됩니다. 파일이 존재하는지 확인하기 위함입니다. 콜백에 null, true를 넘기면 파일이 존재하며 스트리밍할 준비가 되었다는 뜻입니다. 반대로 null, false를 넘기면 파일이 존재하지 않는다는 뜻입니다.</li><li>getManifestStream: .m3u8 파일에 대한 요청일 때 실행됩니다. 콜백에 null과 stream을 넘겨주면 됩니다.</li><li>getSegmentStream: .ts 파일에 대한 요청일 때 실행됩니다. 콜백에 null과 stream을 넘겨주면 됩니다.</li></ul><p>hls-server가 궁금하시다면 <a href="https://www.npmjs.com/package/hls-server">이곳</a>을 참고해주세요.<br><a href="https://github.com/HoseungJang/express-hls-example">github</a>에 예제를 업로드 했습니다. 필요하신분은 확인해주세요.</p><h3>결과물 확인</h3><p>이제 HLS 실습을 위한 모든 준비가 끝났습니다. 서버를 실행시키고 브라우저에서 localhost:3000으로 접속해줍시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*MinDqcztY9mODICmvY84Gg.png" /></figure><p>localhost:3000으로 이동하면 동영상 플레이어가 보입니다.(노래방이 세상에서 제일 재밌습니다.) 이 상태에서 F12를 눌러 Network 탭으로 들어가줍시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*8zbn_-DEacnc8Tv38YHxBQ.png" /></figure><p>동영상 재생을 위해서 .m3u8 파일과 .ts파일 일부를 미리 불러온 것을 확인할 수 있습니다. 이제 동영상을 재생해봅시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*tLvorcRSO1MUM5NhERL9Xw.png" /></figure><p>재생 시간에 맞춰서 .ts파일을 순서대로요청하는 것을 확인할 수 있습니다. HLS를 사용한 동영상 스트리밍 성공입니다.</p><h3>마무리</h3><p>HLS를 간단히 실습해 보았습니다. 위키피디아에 따르면 가장 대중적인 스트리밍 포맷이 HLS라고 합니다. 이번 실습을 통해서 그 이유를 조금이나마 느낄 수 있었던 것 같습니다.</p><p>하지만 동영상을 스트리밍하는 방식도 여러가지고, 각각의 방식에 어울리는 상황도 여러가지일 것입니다. HLS 하나 실습하고 만족하기 보단 다른 방식들도 공부해서 상황에 맞게 적용하는 것이 베스트인 것 같습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46006408a0e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript와 typedi로 의존성 주입 이해하기]]></title>
            <link>https://medium.com/@HoseungJang/typescript%EC%99%80-typedi%EB%A1%9C-%EC%9D%98%EC%A1%B4%EC%84%B1-%EC%A3%BC%EC%9E%85-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0-5d83ef1977f9?source=rss-b4176643244d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d83ef1977f9</guid>
            <category><![CDATA[의존성주입]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[제어권의-역전]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Alvin]]></dc:creator>
            <pubDate>Tue, 21 Apr 2020 06:23:42 GMT</pubDate>
            <atom:updated>2020-04-23T04:00:49.238Z</atom:updated>
            <content:encoded><![CDATA[<h3>개요</h3><p>얼마전, <a href="https://velog.io/@hopsprings2/%EA%B2%AC%EA%B3%A0%ED%95%9C-node.js-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8-%EC%95%84%ED%82%A4%ED%85%8D%EC%B3%90-%EC%84%A4%EA%B3%84%ED%95%98%EA%B8%B0">이곳</a>에서 의존성 주입을 접했습니다. TypeScript/Express로 개발할 때 도움이 많이 될 것 같아서 정리해보려고 합니다.</p><h3>의존성</h3><p><strong>의존성</strong>은 구성 요소들이 서로 의존하는 성질입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*uPNJQXVtRS1jLQ219HbT1w.png" /></figure><p>위 코드에서 Programmer 클래스는 Laptop 클래스에 <strong>의존성</strong>을 띕니다.</p><h3>대표적인 문제</h3><p>구성 요소가 의존성을 띄게되면 <strong>변경에 민감</strong>해집니다.</p><p>위의 예제에서 Programmer가 평범한 Laptop이 아닌 Macbook을 사용하도록 만들고 싶습니다. 이때 아래와 같이 코드를 수정할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*eFarBFrJEZ_Fxc5syvVSxA.png" /></figure><p>Laptop 클래스를 상속받는 Macbook 클래스를 생성했습니다. Programmer 클래스의 laptop 변수가 Macbook 클래스의 객체를 할당받도록 수정해주면 됩니다.</p><p>하지만 문제가 하나 있습니다. Programmer 클래스가 Laptop 클래스에 의존하고 있었기 때문에 Programmer 클래스를 직접 수정해야 했다는 점입니다.</p><p>이렇게 <strong>의존성</strong>은 <strong>하나를 변경</strong>하면 그것에 <strong>의존하는 다른 것들도 모두 변경</strong>하도록 만듭니다.</p><p>그러나 다행히도 우리는 <strong>의존성 주입</strong>을 통해서 문제를 해결할 수 있습니다.</p><h3>의존성 주입</h3><p>의존성 주입이란 말그대로 외부에서 의존성을 주입해주는 것을 말합니다. 아래의 예제를 봅시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*FcGPeCvKr4M9nzLbxifxyw.png" /></figure><p>맨 처음에 보았던 예제에서 <strong>의존성 주입</strong>을 사용해 보았습니다. Programmer 클래스가 의존하던 Laptop 클래스의 객체를 외부에서 주입해주고 있습니다.</p><p>이번에는 Programmer가 Macbook을 사용하게 만들고 싶습니다. 아래의 예제를 봅시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*0cvCETapDiTKv8uRZ4ohcQ.png" /></figure><p>위에서 문제가 발생했던 예제와 차이가 느껴지시나요? Laptop 클래스의 객체 대신 Macbook 클래스의 객체를 주입해주면 Programmer 클래스를 수정하지 않고도 매우 편리하게 변경사항을 적용할 수 있습니다. 이것이 <strong>의존성 주입</strong>을 사용하는 이유입니다.</p><p>하지만 <strong>의존성 주입</strong>만 사용하는 것도 문제를 만듭니다. 그래서 우리는 <strong>의존 관계 역전의 원칙</strong>을 알아볼 것입니다.</p><h3>의존 관계 역전의 원칙</h3><p><strong>의존 관계 역전의 원칙</strong>이란 SOLID 원칙 중 하나로, 변화하기 쉬운 것 보단 변화하기 어려운 것에 의존하라는 원칙입니다.</p><p>예를 들면, 프로그래머들이 <strong>구체적으로 어떤 기종</strong>(Macbook, Gram 등등..)을 사용할지는 변하기 쉬운 것입니다. 그러나 여기서 프로그래머들이 <strong>노트북으로 코딩을 한다는 점</strong>은 변하기 어렵습니다.</p><p>아래의 예제를 봅시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*WGEl_BGlgyv8jkhdE3Pzng.png" /></figure><p>Macbook 클래스와 Gram 클래스가 Laptop 인터페이스를 구현하고 있습니다. 그리고 Programmer 클래스의 생성자는 Laptop 타입의 인자를 받고 있습니다.</p><p>따라서 모든 클래스가 Laptop이라는 인터페이스에 의존하게 되고, 이는 일반적인 의존 관계(하위 클래스가 상위 클래스에 의존)와 다르다는 것을 알 수 있습니다.</p><p>여기서 Macbook, Gram과 함께 삼성 노트북도 사용하고 싶다면 Laptop 인터페이스를 구현하는 삼성 노트북 클래스를 만들면 됩니다. 삼성 노트북 클래스의 인스턴스를 Programmer에게 주입하더라도 어떤 문제도 발생하지 않습니다.</p><p>즉, 이러한 의존 관계는 <strong>유연한 확장</strong>이 가능하게 만들고, <strong>변경이 불필요</strong>하도록 만듭니다. 이는 SOLID 원칙 중 <strong>개방-폐쇄 원칙</strong>이 지켜진 것입니다.</p><p>하지만 아직 만족하긴 이릅니다. 더 아름다운 개발을 위해서 <strong>제어권의 역전</strong>에 대해서 알아봅시다.</p><h3>제어권의 역전</h3><p>의존성 주입만 사용하게 되면 우리가 <strong>직접 의존성을 관리</strong>해야 합니다. 하지만 <strong>클래스가 가질 수 있는 의존성은 무한</strong>합니다. 따라서 새로운 객체를 생성할 때 마다 직접 주입해 주는 것은 <strong>지루하고 비효율적</strong>입니다.</p><p>그래서 의존성 주입 도구인 typedi가 존재합니다. 아래의 예제를 봅시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*mAhlq4o4MsqFwWp0bRjK4Q.png" /></figure><p>이전과 차이가 느껴지시나요? 인스턴스화가 필요한 클래스에 Service 데코레이터를 붙여주고, 필요한 의존성은 클래스 내부에 선언해주면 typedi가 <strong>알아서 의존성을 주입</strong>합니다.</p><p>우리는 직접 의존성의 인스턴스를 생성하지 않아도 됩니다. typedi에게 의존성 정보를 알려주고(constructor에 선언) 필요할 때 요구(Container.get)하면 됩니다.</p><p>즉, 우리가 아니라 <strong>typedi가 제어권을 갖는 주체</strong>로 동작합니다. 이를 <strong>제어권의 역전</strong>이라고 부릅니다.</p><h3>마무리</h3><p>처음으로 서버 인프라와 관련되지 않은 내용의 글을 쓴 것 같습니다. 개선 과정도 좋지만 중요한 개념을 정리하는 것도 좋은 것 같습니다. 덕분에 헷갈리던 부분을 확실하게 알아갈 수 있었습니다. 하루빨리 성장해서 더 많은 지식을 공유하고 싶네요.</p><p>typedi에 대한 자세한 내용은 <a href="https://www.npmjs.com/package/typedi">이곳</a>을 참고해주세요.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d83ef1977f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>