node.jsで同期処理を何度も忘れて、何度も調べなおしてしまうので、コードを貼り付け。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
// npm install mongodb // npm install sqlite3 run(); async function run() { console.log('run 100'); var str = await sleep(1000, 'with await'); console.log(str); // await をつけると同期 console.log('run 200'); var str = sleep(1000, 'without await'); console.log(str); // await をつけないと非同期 console.log('run 300'); requireJSON(); // require はそもそも同期 console.log('run 400'); await readFileJSON(); // fs.readFile では同期指定が必要 console.log('run 500'); readFileSyncJSON(); // fs.readFileSync はそもそも同期 console.log('run 600'); await child_process_whoami(); // 子プロセス console.log('run 700'); await child_process_sakasa_exe(); // 返り値を受け取る console.log('run 800'); await child_process_ffmpeg_exe(); // 画像生成 console.log('run 900'); await mongodb(); // mongodb への接続 console.log('run 1000'); var list = await sqlite3(); // sqlite3 への接続 console.dir(list); console.log('run 1100'); } function sleep(ms, msg) { return new Promise(resolve => { setTimeout(() => { console.log('sleep', ms, msg); resolve('comp setTimeout'); }, ms); }) } function requireJSON() { var json = require('./data.json'); console.log(json); } function readFileJSON() { return new Promise((resolve, reject) => { var fs = require('fs'); var path = "data.json"; fs.readFile(path, 'utf8', (err, data) => { console.log(data); resolve(); }); }); } function readFileSyncJSON() { var fs = require('fs'); var path = "data.json"; var str = fs.readFileSync(path, 'utf8'); console.log(str); } function child_process_whoami() { return new Promise((resolve) => { require('child_process').exec('whoami', (err, stdout, stderr) => { console.log('stdout:', stdout); resolve(stdout); }); }); } function child_process_sakasa_exe() { return new Promise((resolve) => { require('child_process').exec('sakasa.exe "Mizutama Inc."', (err, stdout, stderr) => { console.log('stdout:', stdout); resolve(stdout); }); }); } function child_process_ffmpeg_exe() { var source = 'pcloud640480.exe'; var AppPath = 'C:\\inetpub\\ffmpeg-20180820-78d4b6b-win64-static\\bin\\ffmpeg.exe'; var source = 'pcloud640480.mp4'; var out = source + '_ex_ffmpeg.exe.jpg'; var argument = ' -y -i "' + source + '" -f image2 -vframes 1 -ss 3 -an -deinterlace "' + out + '"'; var cmd = AppPath + ' ' + argument; return new Promise((resolve, reject) => { require('child_process').exec(cmd, (err, stdout, stderr) => { console.log('err:', err); console.log('stdout:', stdout); console.log('stderr:', stderr); //console.log(out); resolve(); }); }); } function mongodb() { var url = 'mongodb://127.0.0.1:27017/'; var collectionName = 'startup_log'; var mongodb = require('mongodb'); const MongoClient = mongodb.MongoClient; return new Promise((resolve) => { MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => { const db = client.db('local'); var collection = db.collection(collectionName); collection.find().toArray((error, documents) => { console.log(documents); resolve(documents); }); }); }); } function sqlite3() { return new Promise((resolve, reject) => { var sqlite = require('sqlite3').verbose(); var db = new sqlite.Database('test.sqlite'); console.log('sqlite3 100'); db.serialize(() => { db.run('CREATE TABLE IF NOT EXISTS pigs(name TEXT, age INT)'); var stmt = db.prepare('INSERT INTO pigs VALUES(?,?)'); stmt.run(["boo", 5]); stmt.run(["foo", 4]); stmt.run(["woo", 3]); stmt.finalize(); console.log('sqlite3 200'); }); console.log('sqlite3 300'); db.serialize(() => { var list = []; db.each("SELECT * FROM pigs", (err, row) => { list.push(row.name + ":" + row.age); console.log(row.name + ":" + row.age); console.log('sqlite3 400'); }, (err, count) => { console.log('sqlite3 comp' + count); resolve(list); }); console.log('sqlite3 500'); }); console.log('sqlite3 600'); db.close(); console.log('sqlite3 700'); }); } |
以下、Windows PowerShellでのコマンド結果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
> node test.js run 100 sleep 1000 with await comp setTimeout run 200 Promise { <pending> } run 300 [ { group: 'pigs', name: [ 'boo', 'foo', 'woo' ] } ] run 400 [ { "group" : "pigs", "name" : ["boo","foo","woo"]} ] run 500 [ { "group" : "pigs", "name" : ["boo","foo","woo"]} ] run 600 stdout: umeha\umeha run 700 stdout: <!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><title>CGI page</title></head><body>.cnI amatuziM</body></html> run 800 err: null stdout: stderr: ffmpeg version N-91646-g78d4b6bd43 Copyright (c) 2000-2018 the FFmpeg developers ~省略(ffmpegの返り値)~ erhead: unknown run 900 [ { ~省略(mongodbで取得したデータ)~ } ] run 1000 sqlite3 100 sqlite3 200 sqlite3 300 sqlite3 500 sqlite3 600 sqlite3 700 boo:5 sqlite3 400 foo:4 sqlite3 400 woo:3 sqlite3 400 sqlite3 comp3 [ 'boo:5', 'foo:4', 'woo:3' ] run 1100 sleep 1000 without await |
参考
Node.jsのMongoClientの仕様が変わってた
MongoClient.connect()時にuseNewUrlParserオプションを与える
node.jsでファイルの読み込み、新規作成、上書き、追記、削除
Node.jsでasyncモジュールを使って同期処理を行う
Node.js + MongoDBを導入する
node.jsでjsonファイルの読み込み
Node.js+express+MongoDB+Mongooseで簡単なjsonサーバを構築するメモ
Node.jsでSQLite3を使ってみる
Node.jsを使った簡単なファイル操作
今更だけどPromise入門