2
1

More than 1 year has passed since last update.

気軽に使えそうなnode.js 4選

Last updated at Posted at 2021-11-17

・開発の補助として、駄菓子感覚で使えそうなネタを集めてみました。
・Node.jsやnpmの導入方法は割愛させていただきます。
・javascriptに関しては、kotlinやswiftを使える方なら雰囲気で書けると思います。
・きっちりめな言語が良い場合はTypeScriptも利用できます。

エンジニアっぽくYouTube動画をごにょごにょする

$ npm init
$ npm install --save-dev ytdl
$ vim index.js
index.js
const fs = require('fs');
const ytdl = require('ytdl-core');
ytdl('https://www.youtube.com/watch?v=xxxxxxxx')
  .pipe(fs.createWriteStream('video.mp4'));
$ node index.js

・実行が終わるとvideo.mp4が生成される
・プログレスバーが欲しい場合は以下を参照

静的htmlを表示

$ npm init
$ npm install --save-dev node-static
$ vim index.html
index.html
<html><body>hello</body></html>
$ ./node_modules/.bin/static 

・ブラウザでlocalhost:8080にアクセスすると、helloが表示される
・index.html以外にもファイルを適当に配置してOK

リバースプロキシ

$ npm init
$ npm install --save-dev http-proxy
$ vim index.js
index.js
var proxy = require('http-proxy');
proxy.createProxyServer({target: 'http://localhost:8080'}).listen(3001)
proxy.createProxyServer({target: 'http://localhost:50021'}).listen(3002)
$ node index.js

・3001を8080、3002を50021にふりわける

CRUD JSONサーバ

$ npm init
$ npm install --save-dev json-server
$ vim data.json
data.json
{
  "user": [
    { 
      "id": 1,
      "name": "aaa"
    },
    { 
      "id": 2,
      "name": "bbb"
    },
    { 
      "id": 3,
      "name": "ccc"
    }
  ]
}
$ ./node_modules/.bin/json-server --watch data.json 

http://localhost:3000/user で全てのuserのjsonを返す

[
  {
    "id": 1,
    "name": "aaa"
  },
  {
    "id": 2,
    "name": "bbb"
  },
  {
    "id": 3,
    "name": "ccc"
  }
]

http://localhost:3000/user/1 でidが1のuserのjsonを返す

{
  "id": 1,
  "name": "aaa"
}

・読み込みだけでなく追加・編集・削除も可能。

以上、開発の補助にお役立て下さい。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1