0
0

More than 1 year has passed since last update.

[Snippet] JavaScript、Node.js

Last updated at Posted at 2021-10-25

これは何?

JavaScriptで「あれってどう書くんだっけ?」を集めたメモです。

時間系

Sleep

  • Return: [void]
const sleep = msec => new Promise(resolve => setTimeout(resolve, msec))

UNIX timeを取得

  • Return: [number]: 1635204475862 (unit: millisecond)
Date.now()

文字列として時間を取得

  • Inputs:
    • TIMESTAMP_MSEC (unit: millisecond): [number]: 1635204475862
  • Return: [string]: "Tue Oct 26 2021 08:27:55 GMT+0900 (Japan Standard Time)"
new Date(TIMESTAMP_MSEC);

Timezoneを考慮した時間を取得

  • Return: [string]: "2021-10-26T20:57:57.911+09:00" (Format: ISO_8601)
const getDateNow = () => {
  const date = new Date()
  const timeOffset = date.getTimezoneOffset()
  const sign = (timeOffset)<=0 ? '+' : '-'
  const rTimeOffset = Math.abs(timeOffset)
  const tz = `${sign}${('00' + Math.floor(rTimeOffset/60)).substr(-2)}:${('00' + rTimeOffset%60).substr(-2)}`
  return new Date(date.getTime() - (timeOffset * 60000)).toJSON().replace(/Z$/, tz)
}

File操作系

ディレクトリ作成(再帰的)

  • Arguments:
    • DIR_NAME: [string]: "/home/hoge/download"
  • Return: [void]
const fs = require('fs-extra');
try {
  fs.mkdirSync(`${DIR_NAME}`, { recursive: true })
} catch(e) {
  console.error(e.message);
}

ファイル存在確認

  • Arguments:
    • FILE_NAME: [string]: "/home/hoge/download/test.txt"
  • Return: [Boolean]
const fs = require('fs-extra');
try {
  if (fs.existsSync(`${FILE_NAME}`)) {
    // アリ
  } else {
    // ナシ
  }
} catch(e) {
  console.error(e.message);
}

ファイルを書き出す

  • Arguments:
    • FILE_NAME: [string]: "/home/hoge/download/test.txt"
    • CONTENT_TEXT: [string]: "aaaa\nbbbb\ncccc"
  • Return: [Boolean]
const fs = require('fs-extra');
try {
  fs.writeFileSync(`${FILE_NAME}`, `${CONTENT_TEXT}`)
} catch(e) {
  console.error(e.message);
}

ファイルの属性取得

  • Arguments:
    • FILE_NAME: [string]: "/home/hoge/download/test.txt"
  • Return: [object]: class-fsstats
const fs = require('fs-extra');
try {
  const fileStat = fs.statSync(`${FILE_NAME}`)
} catch(e) {
  console.error(e.message);
}
0
0
2

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
0
0