반응형
반응형

Object.assign()

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

 

Object.assign() - JavaScript | MDN

Object.assign() 메서드는 출처 객체들의 모든 열거 가능한 자체 속성을 복사해 대상 객체에 붙여넣습니다. 그 후 대상 객체를 반환합니다.

developer.mozilla.org

Object.assign()

Object.assign() 메서드는 출처 객체들의 모든 열거 가능 자체 속성을 복사해 대상 객체에 붙여넣습니다. 그 후 대상 객체를 반환합니다.

const target = { a: 1, b: 5 };
const source = { b: 7, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
반응형
반응형

자바스크립트로 현재시간 timestamp 구하기

console.log( new Date().getTime() );
 

 

반응형
반응형

getDay() 메서드는 지정된 날짜의 요일(0~6)을 반환합니다.

var d = new Date();
var n = d.getDay();

getDay() 메서드는 지정된 날짜의 요일(0~6)을 반환합니다.

참고: 일요일은 0, 월요일은 1 등입니다.

var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var n = weekday[d.getDay()];

 

https://www.w3schools.com/js/js_date_methods.asp

 

JavaScript Get Date Methods

Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1, 1970)
getDay() Get the weekday as a number (0-6)
Date.now() Get the time. ECMAScript 5.

 

 

반응형
반응형

고정 길이의 문자열이 되도록 숫자 앞에 0을 추가하는 방법이 있습니까? 

예를 들어 2자리를 지정하면 5는 "05"가 됩니다.

 

 

Small one-liner function using the ES2017 String.prototype.padStart method:

const zeroPad = (num, places) => String(num).padStart(places, '0')

console.log(zeroPad(5, 2)); // "05"
console.log(zeroPad(5, 4)); // "0005"
console.log(zeroPad(5, 6)); // "000005"
console.log(zeroPad(1234, 2)); // "1234"

Another ES5 approach:


function zeroPad(num, places) {
  var zero = places - num.toString().length + 1;
  return Array(+(zero > 0 && zero)).join("0") + num;
}

zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)

 

https://stackoverflow.com/questions/2998784/how-to-output-numbers-with-leading-zeros-in-javascript

 

How to output numbers with leading zeros in JavaScript?

Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.

stackoverflow.com

 

반응형
반응형

EJS - Embedded JavaScript templating.

<%= EJS %>

https://ejs.co/

 

EJS -- Embedded JavaScript templates

Simple syntax JavaScript code in simple, straightforward scriptlet tags. Just write JavaScript that emits the HTML you want, and get the job done!

ejs.co

Options

  • cache Compiled functions are cached, requires filename
  • filename Used by cache to key caches, and for includes
  • root Set project root for includes with an absolute path (e.g, /file.ejs). Can be array to try to resolve include from multiple directories.
  • views An array of paths to use when resolving includes with relative paths.
  • context Function execution context
  • compileDebug When false no debug instrumentation is compiled
  • client Returns standalone compiled function
  • delimiter Character to use for inner delimiter, by default '%'
  • openDelimiter Character to use for opening delimiter, by default '<'
  • closeDelimiter Character to use for closing delimiter, by default '>'
  • debug Outputs generated function body
  • strict When set to `true`, generated function is in strict mode
  • _with Whether or not to use with() {} constructs. If false then the locals will be stored in the locals object. (Implies `--strict`)
  • localsName Name to use for the object storing local variables when not using with Defaults to locals
  • rmWhitespace Remove all safe-to-remove whitespace, including leading and trailing whitespace. It also enables a safer version of -%> line slurping for all scriptlet tags (it does not strip new lines of tags in the middle of a line).
  • escape The escaping function used with <%= construct. It is used in rendering and is .toString()ed in the generation of client functions. (By default escapes XML).
  • outputFunctionName Set to a string (e.g., 'echo' or 'print') for a function to print output inside scriptlet tags.
  • async When true, EJS will use an async function for rendering. (Depends on async/await support in the JS runtime.Tags
    • <% 'Scriptlet' tag, for control-flow, no output
    • <%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
    • <%= Outputs the value into the template (HTML escaped)
    • <%- Outputs the unescaped value into the template
    • <%# Comment tag, no execution, no output
    • <%% Outputs a literal '<%'
    • %> Plain ending tag
    • -%> Trim-mode ('newline slurp') tag, trims following newline
    • _%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it

 

 

.

반응형
반응형

[Node.js]  Path : 파일 경로를 다루고 변경하는 유틸리티가 포함되어 있다

https://nodejs.sideeffect.kr/docs/v0.10.0/api/path.html

 

Path Node.js v0.10.0 Manual & Documentation

Path# Stability: 3 - Stable This module contains utilities for handling and transforming file paths. Almost all these methods perform only string transformations. The file system is not consulted to check whether paths are valid. Use require('path') to use

nodejs.sideeffect.kr

path.normalize(p)#

'..'와 '.' 부분을 처리해서 문자열 경로를 정규화한다.

슬래시가 여러 개 있는 경우 슬래시 하나로 교체하고 경로의 마지막에 슬래시가 있는 경우에는 유지한다. windows에서는 역슬래시를 사용한다.

path.normalize('/foo/bar//baz/asdf/quux/..')
// returns
'/foo/bar/baz/asdf'

path.join([path1], [path2], [...])#

모든 아규먼트를 합쳐서 최종 경로로 정규화한다. 문자열이 아닌 아규먼트는 무시한다.

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
// returns
'/foo/bar/baz/asdf'

path.join('foo', {}, 'bar')
// returns
'foo/bar'

path.resolve([from ...], to)#

to를 절대경로로 변환한다.

to가 절대경로가 아니면 절대경로를 찾을 때까지 from 아규먼트들을 우측에서 좌측의 순서로 앞에 이어붙힌다.모든 from 경로를 사용한 후에도 절대경로를 찾지 못하면 현재 워킹 디렉토리를 사용한다. 최종 경로는 정규화되고 경로가 루트 디렉토리로 처리되지 않는한 마지막 슬래시는 제거한다. 문자열이 아닌 아규먼트는 무시한다.

이는 쉘에서 cd 명령어를 순서대로 실행한 것과 같다.

path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')

//-- 이는 다음과 비슷하다.:

cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd

//--다른 경로라 존재할 필요가 없거나 파일일 수도 있다는 점만이 다르다.

path.resolve('/foo/bar', './baz')
// returns
'/foo/bar/baz'

path.resolve('/foo/bar', '/tmp/file/')
// returns
'/tmp/file'

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// if currently in /home/myself/node, it returns
'/home/myself/node/wwwroot/static_files/gif/image.gif'

 

path.relative(from, to)#

from에서 to까지의 상대경로를 처리한다.

때로는 두 개의 절대경로를 가지고 있고 하나에서 다른 하나로의 상대경로를 얻어야 한다. 사실 이는 path.resolve의 반대 변환이다. 이 의미를 다음 예제에서 보자.

path.resolve(from, path.relative(from, to)) == path.resolve(to)

//-----------------------------------------------

path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
// returns
'..\\..\\impl\\bbb'

path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
// returns
'../../impl/bbb'

path.dirname(p)#

경로의 디렉토리이름을 반환한다. Unix의 dirname 명령어와 비슷하다.

path.dirname('/foo/bar/baz/asdf/quux')
// returns
'/foo/bar/baz/asdf'

path.basename(p, [ext])#

경로의 마지막 부분을 반환한다. Unix의 basename 명령어와 비슷하다.

path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'

path.basename('/foo/bar/baz/asdf/quux.html', '.html')
// returns
'quux'

path.extname(p)#

경로의 마지막 부분의 문자열에서 마지막 '.'에서부터 경로의 확장자를 반환한다. 경로의 마지막 부분에 '.'가 없거나 첫 글자가 '.'이라면 빈 문자열을 반환한다. 

path.extname('index.html')
// returns
'.html'

path.extname('index.')
// returns
'.'

path.extname('index')
// returns
''

path.sep#

플랫폼의 파일 구분자. '\\'나 '/'이다.

'foo/bar/baz'.split(path.sep)
// returns
['foo', 'bar', 'baz']

 

path.delimiter#

플랫폼에 특화된 경로 구분자인 ;나 ':'이다.

 

console.log(process.env.PATH)
// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'

process.env.PATH.split(path.delimiter)
// returns
['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']

반응형

+ Recent posts