facebook twitter hatena line email

「Javascript/nodejs/技術メモ」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(for)
(callback)
行57: 行57:
 
}
 
}
 
registerCallback(onLoadResponse);
 
registerCallback(onLoadResponse);
 +
</pre>
 +
 +
===callbackモジュール化===
 +
main.js
 +
<pre>
 +
const httprequest = require('./httprequest.js');
 +
function onLoadResponse(responseType) {
 +
    console.log(responseType);
 +
}
 +
httprequest.registerCallback(onLoadResponse);
 +
</pre>
 +
 +
httprequest.js
 +
<pre>
 +
exports.registerCallback = function (callback) {
 +
    callback('success');
 +
}
 
</pre>
 
</pre>

2019年8月10日 (土) 14:53時点における版

公式ドキュメント(日本語

http://nodejs.jp/nodejs.org_ja/api/

モジュール化

  • foo.js
var circle = require(__dirname + '/circle.js');
console.log( 'The area of a circle of radius 4 is '
           + circle.area(4));
  • circle.js
var PI = Math.PI;
exports.area = function (r) {
  return PI * r * r;
};
exports.circumference = function (r) {
  return 2 * PI * r;
};

a-z乱数文字生成

a-zから8文字取得

var S="abcdefghijklmnopqrstuvwxyz"
var N=8
var str = Array.from(Array(N)).map(()=>S[Math.floor(Math.random()*S.length)]).join('')
// kwaqghgs

参考:https://qiita.com/fukasawah/items/db7f0405564bdc37820e

objectをjsonで返す

var key = 1234;
var obj = {
      name: "taro",
      key: key
}
var jsontext = JSON.stringify(obj);

現在のunixtime

var date = new Date() ;
var unixtimems = date.getTime() ;
var unixtime = Math.floor( unixtimems / 1000 ) ;
console.log('unixtime=' + unixtime);

for

for (let i = 0; i < users.length; i++) {
   console.log(users[i])
}

callback

function registerCallback(callback) {
    callback('success');
}
function onLoadResponse(responseType) {
    console.log(responseType);
}
registerCallback(onLoadResponse);

callbackモジュール化

main.js

const httprequest = require('./httprequest.js');
function onLoadResponse(responseType) {
    console.log(responseType);
}
httprequest.registerCallback(onLoadResponse);

httprequest.js

exports.registerCallback = function (callback) {
    callback('success');
}