2012年12月4日火曜日

Node.jsでめっちゃ簡単に動画をストリーミング配信しよう

前回の続きです。
作業ディレクトリに移動しましょう。
高木はtestディレクトリの中にserver.jsがある状態です。

今回はhtml5で登場したvideoタグを使って動画をストリーミング配信します。
そのためvideoタグを使ったhtmlファイルを用意します。


  • htmlファイルの用意

中身はこんな感じです。


10行目〜13行目がvideoタグです。10行目のcontrolsをつけると再生ボタンやシークバーなどが現れます。
11行目のsourceタグに動画の場所を書きます。今回のコードだとserver.jsがある場所と同じところですね。
typeにはmimeタイプを書きます。


  • 前回のserver.jsの書き換え
サーバのコードを変更しましょう。


前回は

res.write('好きな文字列');

でクライアントに文字を送りましたが、今回はhtmlファイルを送ります。
  • クライアントからのリクエストが動画の送信かどうかチェックする
  • 動画の送信でない場合、送りたいhtmlを読み込む
  • 読み込んだファイルの中身をクライアントに送る
という流れで行きたいと思います。

そのために7行目のように「fs」モジュールを読み込みます。
11行目でリクエストが動画ではないことをチェックして、13行目のようにfs.readFileにhtmlファイルへのパス(./video.html)を渡します。
ファイルを読み込めるとコールバックのdataに渡されるので、それをres.writeで書きこめば終わりです。

20〜26行目は動画のストリーミングです。
20行目のfs.createReadStrem(path)はpathで指定したファイルの読み込みストリームを作ります。今回はこのpathに配信したい動画のパス(./test.mp4)を書きます。

21〜24行目はエラーイベントが起こった時の処理です。

26行目のreadStream.pipe(destination)は作成した読み込みストリームをdestinationで指定した書き込み先に接続します。
このdestinationに「res」を指定することでリクエストがあったクライアントに読み込んだ動画をそのまま流せます。

じゃあ実行しましょう!

こんな感じで3つのファイルがあるはずです。

node server.js

で実行してブラウザから http://localhost:30000 にアクセスします。

このように再生できるはずです。


これからNode.jsをはじめる人の入門として軽く見てくれればいいなーと思ってこの記事を書きました。
特に3年生の後輩でサーバー側やウェブアプリに興味のある人はやってみてはどうですか

76 件のコメント:

  1. Students find International Relations Research Paper Services as being of great assistance since they are able to complete their custom international research papers and international relations essay services on time.

    返信削除
  2. There is a reliable Healthcare Assignment Writing Service that is very popular for students in search of healthcare coursework writing services and nursing essay writing help services.

    返信削除
  3. The ultimate goal of entrepreneurship coursework writing services is to provide Entrepreneurship Writing Services and entrepreneurship essay writing services since entrepreneurship assignments writing service seekers lack time to complete their entrepreneurship term paper writing services.

    返信削除
  4. There are reliable PowerPoint Presentation Writing Services that are very popular for students in search of powerpoint presentation preparation services and pay for powerpoint presentations.

    返信削除
  5. American literature review writing service seekers have an advantage of hiring the best American literature research writing services that are familiar with American literature essay writing services for their American Literature Writing Services.

    返信削除
  6. Your post is very knowledgeable. Thank you I am an Academic Writer & I provide Assignment Help Service For Students. I’ve Top Assignment Experts If Any Students Wants to Help So Kindly Visit My Website. aol mail login | yahoo mail login |
    yahoo mail login | cash app login | www.amazon.com/mytv |
    cash app login | amazon login

    返信削除
  7. Amazon Prime is a top of the pedigree Television Based App tote taking place giving a lot of on the subject of-demand and live movies and TV shows, especially without any advertisements.
    visit www.amazon.com/mytv or www.primevideo.com/mytv and enter Amazon activation code to activate amazon prime videos on your smart tv and pc. Read More click below

    amazon.com/mytv
    amazon.com/mytv
    amazon.com/mytv
    amazon.com/mytv
    amazon.com/mytv

    返信削除
  8. Amazon Prime is a top of the pedigree Television Based App tote taking place giving a lot of on the subject of-demand and live movies and TV shows, especially without any advertisements.
    visit www.amazon.com/mytv or www.primevideo.com/mytv and enter Amazon activation code to activate amazon prime videos on your smart tv and pc. Read More click below

    amazon.com/mytv
    amazon.com/mytv
    amazon.com/mytv
    amazon.com/mytv
    amazon.com/mytv

    返信削除
  9. The best way to watch Amazon Prime Video on talking your gadget is to enroll your gadget at amazon.com/mytv by enter the register

    code displayed on your TV Screen. This will serve you to watch your Prime Video shows and films in regards to the request for your

    number one gadget as capably as at your favored period. Amazon Prime Video is currently simple to use for through and through the

    gadgets which are qualified for getting to it. Amazon Video expanded the rundown of their qualified gadgets because of the substantial

    interest of the Prime video clients. To watch Prime Video in con to talking your gadget you should have a record viewing the gadget and

    just as you should have the membership.

    www.amazon.com/mytv

    返信削除
  10. Thank you for this great read. I absolutely enjoyed every bit of your content. I've got this page bookmarked to come back for more ideas. Romantic Text Messages

    返信削除
  11. Wonderful article! We will be linking to this great article on our site. Keep up the good writing. See instagram usernames not yet taken

    返信削除
  12. Thanks for sharing your thoughts. I truly appreciate your efforts and I will be waiting for your next post. See birthday message to a boss

    返信削除
  13. This is really an excellent post. Your blog is really good and has always good and interesting content. Thank you for sharing this with us. Also, check out chromecast av receiver

    返信削除
  14. Streaming online video content is trending nowadays because people are switching to modern ways of getting entertained. They subscribe to different streaming services such as Netflix, Hulu, and more. One such streaming service among many others is Amazon Prime. This service not only gives you the eligibility to stream different videos but also lets you use many other features that come along with it. And, all of this can be done by getting and redeeming amazon.com/mytv

    amazon.com/mytv
    amazon.com/mytv enter code



    返信削除


  15. Nowadays people are switching to modern ways of getting entertained. They subscribe to different streaming services such as Netflix, Hulu, and more. One such streaming service among many others is Amazon Prime. This service not only gives you the eligibility to stream different videos but also lets you use many other features that come along with it. And, all of this can be done by getting and redeeming amazon.com/mytv

    amazon.com/mytv
    amazon.com/mytv enter code
    Amazon com mytv

    返信削除
  16. Steps to activate ESPN using Espn.com/activate. Switch on the device and launch an ESPN channel or application. &amp
    https://www.espn-comactivate.com
    https://hbomax-maxtvsign.com/
    hbomax.com/tvsignin

    返信削除
  17. HBO Max is a TV broadcasting service offered by American premium cable network HBO. Through either the HBO Maxwebsite, or apps on mobile devices, video game consoles, and digital media players, HBO subscribers can stream video and TV shows, including past and current content.
    hbomax.com/tvsignin
    https://hbomax-maxtvsign.com/
    https://www.espn-comactivate.com
    Espn.com/activate

    返信削除
  18. Hydrogen is a chemical element, which is known to be the lightest element in the periodic table. Hydrogen is the most widely available chemical substance in the universe, constituting roughly 75% of all baryonic mass.

    Hydrogen Production Cost Report

    返信削除
  19. Syngas, also known as synthesis gas, is a fuel gas. It is a mixture of gases that are composed of primarily hydrogen, carbon monoxide, and very often some carbon dioxide.

    Syngas Production Cost Report

    返信削除
  20. visit Espn plus activate, and enter the 6-character activation code. After entering the code on the web site,visit Activate ESPN

    返信削除
  21. Ethylene, also known as ethene or green ethylene, is an example of a hydrocarbon. It is a colourless gas that is also flammable and has a faint sweet and musky odour. Ethylene is a crucial natural plant hormone and is used widely in agriculture to force the ripening of fruits.

    Ethylene Production Cost

    返信削除
  22. Nylon 6 or polycaprolactam is a polymer that was developed by Paul Schlack at IG Farben. It was developed to reproduce the properties of nylon 6,6 without altering the patent on its manufacturing.

    Nylon 6 Production Cost

    返信削除
  23. xfinity.com/authorize is an official website that allows clients to access the Xfinity Gateway In fact, customers can discover the best cable, music, etc You will need to connect and activate your modem with your Comcast xfinity activate once you have it installed. xfinity.com/activate have made all reasonable attempts to offer latest and precise information and facts for the readers of this publication.

    返信削除
  24. hbomax.com/tvsignin is a premium streaming app all of HBO, app that combines all of HBO with even more must-seeclassic TV favorites, blockbuster movies, and new Max Originals with the greatest collection of movies, family & kid shows Get hbomax.com/tvsignin code at no
    extra charge with select wireless, TV & Internet plans.You'll get hbomax.com/tvsignin activate and On Demand, plus access to the new HBO Max app to stream it all.

    返信削除
  25. http://blog.t-lab.cs.teu.ac.jp/2012/12/dwr.html
    http://www.sinlung.com/2015/08/autonomous-councils-key-to-naga-deal.html
    http://blog.litecigusa.net/2014/04/what-is-drip-tip.html
    https://www.tusatphongthuy.com/2021/01/ket-sat-dien-tu-van-phong-ks80-thanh-hoa.html
    https://thepinkpineappleblog.blogspot.com/2018/01/my-favorites-cozy-sweaters-for-this.html
    https://tech.dreampirates.in/2015/08/microsoft-changes-web-access-to-on-web.html
    http://apiedeaula.blogspot.com/2010/01/glogs-para-que-os-quiero-ejemplos-de.html
    http://zhazhda-tvorchestva.blogspot.com/2019/05/blog-post_29.html
    http://fan.fc-anji.ru/blogs/blog/guest/13972.html
    https://belgischkookrecepten.blogspot.com/2015/01/preisoep-recept.html

    返信削除
  26. Amazon is not only the pioneer of the e-commerce world but also lets you take your entertainment to the next level with its Prime Video services. You can easily stream the Prime Video shows on your device by activating it via amazon mytv.www.amazon.com/mytv | cash app login

    返信削除
  27. geeksscan I appreciate you for this article this is such a wonderful blog Thanks for posting this Read our blog It is related to technology It helps you to solve your issues that you are facing. This is our latest article visit here guest post site Activate NFL Online at nfl.com/activate

    nfl activate
    nfl.com activate
    nfl.com/activate



    返信削除
  28. Install ESPN through your Roku device - You can find ESPN by browsing through the Sports category after selecting Streaming Channels from your Roku's home screen. However, it may be faster to search for the channel. Select the Search option from your Roku's home screen, then start typing "espn." ESPN should appear as a result before you are done typing it in. Highlight ESPN, press OK on your remote, then select Add Channel and press OK again. Now return to your Roku's home screen and ESPN will be at the very end of your channel list.
    espn.com/activate
    espn activate
    espn plus activate

    espn.com/activate
    espn activate
    espn plus activate

    espn plus activate
    espn activate
    espn.com/activate

    返信削除


  29. If you  use YouTube  on smart devices like Roku, Apple TV, Fire TV, Xbox 360, and Samsung Tv, you get the entertainment services with unlimited data, online video and movies or other benefits. To youtube activate account, you would simply install it on your device and enter the 8 digit verification code on here YouTube.com/activate and then you can enjoy the youtube channel with this app. Enter the code here youtube.com/activate code

    返信削除

  30. really infomative and eduvcative article thanks publisher for sharing this info with us zero gravity massage chair
    whatsaup flippzilla

    返信削除
  31. Thank you so much for taking your time to write and share this very intriguing post, this is excellent erudition article, very useful, informative and educating, Thanks for sharing. Nigerian army recruitment

    返信削除
  32. affordable seo company in usa. If you want any tech support than your are the right way techiespost provide many kind of software solutions and we are the top website development companies in usa which give you the higher quality of software which you deserve.

    返信削除
  33. I seriously love your site. Pleasant colors & theme. I simply stumbled upon your blog and wished to mention that I’ve truly loved surfing around your weblog posts. Check this out too uniben post utme past questions and answers pdf

    返信削除
  34. I'm extremely impressed along with your writing abilities as neatly as with the format on your blog. Anyways, keep up the nice quality writing, it is rare to peer a nice weblog like this one these days. Thanks for sharing. Check easy infoblog

    返信削除
  35. This is a very useful and important information, it was so useful to me and other readers, thank you for always feeding the readers with interesting and useful information, your blog is indeed doing very well, kudos, meanwhile you can checkout this infoguide

    返信削除
  36. This is a very useful and important information, it was so useful to me and other readers, thank you for always feeding the readers with interesting and useful information, your blog is indeed doing very well, kudos, meanwhile you can checkout this dstv packages south africa prices 2021

    返信削除
  37. Get to know the process to do Amazon prime video login close by the strategy in the first place using your Amazon Prime enrollment and start it on Amazon My TV. Essentially hold fast to the quick headings and come out as comfortable with the method to use Primevideo.com/mytv code. There are three fundamental systems using which you can impel your enrollment.
    Read more…
    www.amazon.com/mytv

    返信削除

  38. The most effective method to purchase Viagra on the web. Buy Viagra Online and nonexclusive
    sildenafil are physician endorsed drugs, so you'll have to counsel a specialist before purchasing.
    It is very conceivable to purchase Viagra online modest,order Viagra regardless of whether you buy a marked medication.
    To buy Viagra online. Get up to 20% markdown on professionally prescribed medication Viagra 50mg Tablet 2'S on the web.

    返信削除
  39. nvvsvc.exe it occur on runtime error and stoped working you can uninstall that Nvidia graphic and then go thier official site and download it driver then you will never get nvvsvc.exe virus again.

    返信削除
  40. I ordered to do my excel homework https://essaysprofessors.com/excel-homework-help-from-professors.html on programming microprocessor systems. Usually I did all by myself, but it turned out to be very difficult.

    返信削除
  41. Your blogs are great. Are you also searching for Help with my Math assignment? we are the best solution for you. We are best known for delivering quality essay writing services to students without having to break the bank

    返信削除
  42. Your blogs are authentic and great. Are you also searching for cheap nursing writing company? we are the best solution for you. We are best known for delivering quality essay writing services to students without having to break the bank

    返信削除
  43. This is quite a .good blog. Keep sharing. I love them Are you also searching for nursing paper writing service ? we are the best solution for you. We are best known for delivering nursing paper writing services to students without having to break the bank.

    返信削除
  44. 바카라사이트 I love what yyou guys are up too. This kinnd of clever work and coverage! Keep up tthe good works guys I’ve included you guys to blogroll.Also visit my web blog

    返信削除
  45. 카지노사이트 It’s hard to find knowledgeable people on this topic, but you sound like you know what you’re talking about! Thanks.

    返信削除
  46. Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming. 스포츠토토

    返信削除
  47. Hi there, this weekend is pleasant in favor οf me,
    since this moment i am reading this grеat educational article һere
    аt my hοme.
    토토사이트

    返信削除
  48. Click Here->>Buy Xanax Online without Prescription
    Nervousness is among the most pervasive mental issues in the United States, many individuals who have this condition discover help by taking meds like Xanax. Authorities on the matter agree, around 40 million individuals in the US have an uneasiness issue. Notwithstanding, just about 37% of them get treatment, which is as yet countless individuals. It makes Xanax one of the most recommended meds in the US. While individuals need a remedy to purchase this medication from a neighborhood drug store, they discover a lot of sites that give the choice to arrange Xanax online without a solution.
    Read more…
    Buy Xanax Online Without Prescription

    返信削除
  49. We advise wonderful assistance for AOL Mail. We have a unit of extremely proficient technicians, who can benefit users handling issues during AOL mail sign in now. AOL email login page

    返信削除
  50. Amazon Prime Video is truly a paid subscription-based platform, so unsubscribed folks aren't used to seeing such a thing in the family savings for the stage. Even the www.amazon.com/mytv enter code app is not difficult to do for every entry from those eligible platforms, so it won't track any difficulties even if you activate your device.

    返信削除
  51. McAfee web security offers several levels of insurance. Of course settings, it calls for every product application and records on the run. This can get irritating and tedious: Mcafee messages and internet security suggestions are not particularly illuminating. We are also concerned about some of the standard activities selected. Follow same mcafee.com/activate web address for more help.

    返信削除
  52. mcafee.com/activate is the perfect place to redeem your activation code and activate your McAfee antivirus. McAfee is a leading antivirus solution that protects your data from cyber attacks and Internet viruses. From web security to system tuning, McAfee is a reliable program that has everything you would expect from top-notch, cutting-edge antivirus software.

    返信削除
  53. Use your Microsoft account through office.com/setup for everything you want to with Microsoft 365. Create an account or use the account of services such as OneDrive, Skype, Outlook, or Xbox Live. Use the site microsoft365 com setup to download and install microsoft365.com/setup that will allow you to use multiple apps like Word, Excel, OneNote, PowerPoint, or more.

    返信削除
  54. Use your Microsoft account through office com setup for everything you want to with Microsoft 365. Create an account or use the account of services such as OneDrive, Skype, Outlook, or Xbox Live. Use the site microsoft365 com setup to download and install Microsoft 365 setup that will allow you to use multiple apps like Word, Excel, OneNote, PowerPoint, or more.
    microsoft365.com/setup
    office.com/setup

    返信削除
  55. Enjoyed reading your post keep sharing such amazing post will come back to read more.

    Regards

    fubo.tv/connect
    www.fubo.tv/connect
    www.primevideo.com/mytv
    primevideo.com/mytv

    返信削除
  56. ESPN is the first company that works as a medium for bringing live sports online so that one can watch their favorite sports anytime or anywhere. To know more about the ESPN subscription plans or any other info visit espn.com/activate. If you want to know more about it feel free to get the valuable information from our website instantly.
    espn.com/activate

    返信削除

  57. Canon printers have always been the most popular and widely used printing devices that include various great printing features. They are easy to set up and use for anyone with any smart device. If you want to know more about the Canon printers, you must visit its official website now via ij.start.canon.
    ij.start.canon

    返信削除
  58. You will need to sign into your Amazon Prime Account during the activation phase. It is essential to have an Amazon Prime Account created. This account is only activated by a free login.
    amazon.com/code
    amazon.com/mytv
    www.amazon.com/mytv
    primevideo/mytv
    amazon.com/redeem

    返信削除
  59. Amazon Prime Video allows clients to download their top shows and videos to view later. This option is great for clients who want to enjoy Amazon Prime Video in disconnected mode. If you have registered your devices using amazon.com/mytv, you will be able to view the downloaded videos immediately on your device. Follow the below steps to download your top-rated videos from Amazon Prime Video.
    amazon.com/mytv
    amazon.com/redeem
    amazon.com/code
    amazon.com/mytv

    返信削除
  60. Hello. I am happy to visit your blog. I often use different services for my learning. I found who can do my homework for me cheap https://elitewritings.com/do-my-homework-for-me.html. I am very happy to be a good student. I often get what I need.

    返信削除

  61. If you're trying to activate into your Tubi account on a smart TV or device connected to your TV and you see an activation code on your TV screen, please make sure you open a web browser (e.g. Chrome, Firefox, Safari) on a separate device and visit
    tubi.tv/activate. The code must stay visible on your TV screen during this process.If you already have a Tubi account, click on the Sign in link.Afterward, you’ll be directed to a new screen (pictured below) where you can enter the activation code that is displayed on your TV screen. After you’ve
    Tubi.tv/activate Enter Code on the webpage, it may take a few minutehs for your TV screen to refresh, so please be patient!

    返信削除
  62. もちろん、ビデオはこの記事よりも優れています。 ただし、tiktokで動画を宣伝したい場合は、あなたがすべきTiktokの「いいね」の購入。

    返信削除
  63. If you are new to Amazon Prime or have recently subscribed to it, you can watch all its amazing stuff on your Roku, Chromecast, Amazon Fire TV, and other similar streaming devices by activating your PrimeVideo. In this blog, you will not only learn how to activate www.amazon.com/mytv but also know the topnotch features of Amazon Prime, compatible devices, and more.

    Visit here : amazon.com/mytv

    返信削除
  64. Amazon Prime Video is a paid subscription platform. Therefore, people without a subscription are not used to looking at anything in a savings account on this platform. The www.amazon.com/mytv app is easy to do something for every income of the qualifying platforms, so you won't find any difficulty even if you activate your device. In this article, you will learn how to log into amazon.com/mytv and how to bring your device to watch content from amazon.com/mytv Prime Videos.

    返信削除

  65. To access Activate SHOWTIME Anytime on your streaming device or Smart TV you need a SHOWTIME subscription from a participating TV provider or streaming service, along with a high-speed internet connection.
    Launch the SHOWTIME Anytime app on your smart TV, streaming Device.Navigation to any program and select 'Play' or select 'Activate'from the setting menu. If you are having problem logging into showtime Anytime , or any other issue width your username or password, Please contact your Tv provider.

    返信削除


  66. Getposttop - best blog for technology and online marketing read latest news and blogs about the technology , health, online markenting, business and finance , read best quality are articlehere.
    Get post top -Technology and online marketing blog. Get method is used to appends from date to URL in name or value pair latest Blog. If you use Get , the length of URL will remain limited.It help users to submit to bookmark the result guest posting. Get is better for the latest articl es data which does not require any security or having images or word documents.


    返信削除
  67. Amazon Prime is an annual membership from amazon.com that includes shipping benefits as well as a bunch of other services. So, first and foremost you get free today shipping on qualifying items and it’s includes a lot of items which means you are going to get fast shipping all year long without paying any extra for it.

    www.amazon.com/mytv

    返信削除
  68. Amazon prime can be found to owners through amazon com/mytv of flowing programs and apparatus. On amazon prime you are able to stream movies and television episodes on amazon videu program. You can enjoy amazon prime video on diffrent platforms like fire television, smart-tv, streaming media player, video games console, cell phone or tablet computer. You can easily activate your amazon prime you just need to follow the simple instructions and go to www.amazon.com/mytv to activate amazon Prime Video on your TV. You just need to enroll your compatible device at mazon.com? Just go to the site www.amazon.com/mytv and observe the guidelines to fill out the enrollment of your device, then it is possible to begin appreciating Amazon Prime Instant Video service for free. You need to make use of the 6 digit amazon MY TV code to get enrollment of one’s apparatus.

    a href="https://mytvlink-code.com/amazon-com-mytv/">www.amazon.com/mytv</a

    返信削除
  69. Know the full cycle for enacting Amazon Prime. Adhere to the straightforward guidelines and go to www.amazon.com/mytv to actuate amazon Prime Video on your TV. There are three simple ways of enacting Amazon Prime Video. Would you want to enlist your viable gadget at mazon.com? Simply go to the site www.amazon.com/mytv and notice the rules to finish up the enlistment of your gadget, then, at that point, it is feasible to start liking Amazon Prime Instant Video administration for nothing. You need to utilize the 6 digit amazon MY TV code to get enlistment of one's device.
    Reach out us: www.mytvlink-code.com/amazon-com-mytv

    返信削除
  70. Complete Trend Micro Activation from www.trendmicro.com/activate using the product key. Enter your activation code and sign in to download its products. Make sure you accept the Trend micro license Agreement you receive on www.trendmicro/activate to register your product securely. Use your Trend Micro license to protect several computers with the Trend Micro security program.

    返信削除
  71. The process to set up PIXMA ts3122 starts from ij.start.canon/ts3122 and download the latest full driver & software package for PIXMA TS3122. You can learn to set up this multifunction printer model. Instructions on this page include everything from printer unpacking, installation, configuration, WiFi network establishment to complete canon printer drivers setup.The setup process for every Canon model is almost similar, however the download through https //ij.start.cannon or http //ij.start.cannon and installation process may differ. Let’s get started.ij.start canon is the manufacturer site to download Canon printer drivers. Install and set up Canon Printer from ij.start.canon | canon.com/ijsetup | cannon/ijsetup

    返信削除
  72. Its a really interesting and informative article for me. I appreciate your work and skills. Thanks for sharing! Beth Dutton Fur Coat

    返信削除