やっぱりjsが好き! 続きを読む
Node
【Node】バックグラウンドで動作してしまったサービスを停止する方法
さくらのリモートコンソールで node app.js でいつも通り放置しといたら案の定バックグラウンドへ
※動作テストしてたです。
とりあえずサービス起動してるか確認して停止させるまでの備忘録
$ lsof -i -n -P
$ kill -9 [PIDの番号]
// 追記$ fg
【Node】mongoose-auto-incrementの使用
mongoで連番を使うmodule
var mongoose = require("mongoose"); var Schema = mongoose.Schema; var autoIncrement = require("mongoose-auto-increment"); var db = mongoose.connect("mongodb://localhost/testdb", function(err){ if(err){console.log(err);} }); autoIncrement.initialize(db); var testSchema = new Schema({ author: { type: Schema.Types.ObjectId, ref: 'Author' }, name: String, date: Date }); testSchema.pre("save", function(next){ this.date = new Date(); next(); }); testSchema.plugin(autoIncrement.plugin, 'Test'); var Test = mongoose.model("Test", testSchema);;
だいたいこんな感じに。 _idの上位4バイトがTimeStampになっているらしいけど使わないので。
{ "_id" : 0, "date" : ISODate("2014-07-08T08:31:11.509Z"), "id" : "hoge", "_id" : ObjectId("53bbac4f3a506a3f170c5475"), "__v" : 0 }
【Express】REST
「RESTfulな*」とか書けばいいのだろうか、知らない。
method-overrideを使えば良いらしいので使う.
var bodyParser = require('body-parser'); var connect = require('connect'); var methodOverride = require('method-override'); // body-parserを上に。 app.use(bodyParser.urlencoded()) app.use(methodOverride(function(req, res){ if (req.body && typeof req.body === 'object' && '_method' in req.body) { // look in urlencoded POST bodies and delete it var method = req.body._method delete req.body._method return method } })); // あとは適当に、req.bodyで取得可 app.get("/hoge", ~ app.post("/fuga", ~ app.put("/piyo", function(req, res){ res.send(req.body); }); app.delete("/hogehoge", ~
【Node】req.paramsとreq.bodyの違い
2つの違いを探すのはなにかおかしい気がするけど僕がここで迷ったので記事にする。
[req.params]
app.get("/hoge/:id", function(req, res){ console.log(req.params.id); });
要するにURLの指定された場所を見てるようだ。
[req.body]
var bodyParser = require('body-parser'); app.use(bodyParser()); app.post("/hoge", function(req, res){ console.log(req.body); res.send("test") });
こっちがPOSTしたもの取ってくる奴
※用語各種は理解度が怪しいので使わない
【Express】画像の表示
ここまで辿り着くの長かった。
馬鹿だからね、仕方ないね。
var express = require('express'), app = express(); // テンプレートエンジン、今回はejs app.set("views", __dirname + "/views"); app.set("view engine", "ejs"); // これを指定することによって静的ファイルが見れる。 // ファイルの置き場所はpublicの中、css、img、javascript等はこの中に入れれば見れる。 app.use(express.static(__dirname + '/public')); app.get("/", function(req, res){ res.render("index"); }); app.listen(3000);
|-app.js
|-package.json
|-public
||-style
||-image
||-javascript
|-views
||-index.ejs
|-node_modules
// 追記
// なぜこれで表示できたのか謎、4.xだったのに。
var path = require("path"); app.use(express.static(path.join(__dirname, 'public')));
【Express】テンプレートの作成方法と Macのポートスキャン
npm install -g express npm install -g express-generator // -e でejsを使用します、と express -e test
ディレクトリ移動してから
// package.jsonの中に書いてあるmoduleをインストールしてくださる npm install npm start
何故か3000番ポートで見れた。
/bin/www
の中に記述されてた。
あとポートスキャンのやり方
finderで[ネットワークユーティリティ]で検索して一番右のportsscan
【Express】POST機能の実装
var express = require('express'), // formの値を受け取るためのもの。4.xからこちらを使用。 // $npm install body-parser bodyParser = require('body-parser'), // errorを出すためのもの。4.xからこちらを使用 // $npm install morgan morgan = require('morgan'), app = express(); // テンプレートエンジンの指定とそのディレクトリの指定 app.set("views", __dirname + "/views"); app.set("view engine", "ejs"); // 上から順番に読み込まれる。 app.use(bodyParser()); app.use(morgan()); app.use(express.static(__dirname + "/public")); // http://localhost/ に入った時に呼び出される。 app.get("/", function(req, res){ // index.ejsを表示させる。 res.render("index"); }); // // // // app.post("/hoge", function(req, res){ res.send(req.body.name); });
【Socket.io】roomの作成と参加
socket.ioのroom機能のメモ
var io = require("socket.io"); io.on("connection", function(socket){ // roomへ参加 socket.join( "roomName" ); // 特定のroomへbroadcast送信 socket.broadcast.to( "roomName" ).emit("from server", "hoge"); // 特定のroomの全員に送信 socket.to( "roomName" ).emit("from server", "fuga"); });
socket.io 基礎
基本的なもののまとめ。
サーバー
var app = require("http").createServer(handler), io = require("socket.io")(app), fs = require("fs"); // port番号の設定(1337) app.listen(1337); function handler(req, res){ fs.readFile(__dirname + "/index.html",function(err, data){ if(err){ res.writeHead(500); return res.end("Error loading index.html"); } res.writeHead(200); res.end(data); }); } io.on("connection", function(socket){ // ここに置くと、接続してきたクライアントのみに"hello"というテキストを"first"に送る。 socket.emit("first", "hello"); // broadcastを使用すると、"hi"というテキストを"second"に送る。 socket.broadcast.emit("second", "hi"); // 接続しているクライアント全てに"bye"を送る io.sockets.emit("third", "bye"); // クライアントから"hoge"でデータが送られてきた際に実行される。 socket.on("from client".function(data){ // 送られてきたデータはdataに格納される。jsonも可 console.log(data.test); // てすと }); });
クライアント
var socket = io("http://localhost"); socket.on("first", function(data){ console.log(data); // "hello" }); socket.on("second", function(data){ console.log(data); // "hi" }); socket.on("third", function(data){ console.log(data); // "bye" }); socket.emit("from client", { test: "てすと" });