Node.js에서 윈도우즈 외부 경로 파일 읽기 — 윈도우즈에선 / 도 구분자로 받지만 path 메서드는 \ 로 만든다.1
const path = require('path')
const fs = require('fs').promises
// 슬래시 사용 (윈도우즈는 / 와 \ 를 둘 다 구분자로 받는다)
// ('C:/Users/username/Documents/file.txt')
// 또는 백슬래시 이스케이프
// ('C:\\Users\\username\\Documents\\file.txt')
// 권장: path.join 사용 (크로스 플랫폼)
path.join(process.env.USERPROFILE, 'Documents', 'file.txt')
// path.resolve로 절대 경로 생성
path.resolve('../../Documents/file.txt')
path.normalize()는 디렉토리 트래버설을 막지 못한다 — .. 를 풀기만 해서 normalize('../../etc/passwd') 는 그대로 '../../etc/passwd' 다.2 사용자 입력이면 path.resolve(base, input) 결과가 base + path.sep 로 시작하는지 확인한다.
Footnotes
-
Path - Node.js: “On Windows, both the forward slash (
/) and backward slash (\) are accepted as path segment separators; however, thepathmethods only add backward slashes (\).” ↩ -
path.normalize - Node.js: “The
path.normalize()method normalizes the givenpath, resolving'..'and'.'segments.” ↩
turf.js로 좌표가 영역 내에 있는지 확인 — GeoJSON 좌표는 [경도, 위도] 순이고, 폴리곤 고리는 첫 점으로 닫는다.1
const turf = require('@turf/turf')
const polygon = turf.polygon([
[
[-73.981, 40.768],
[-73.981, 40.764],
[-73.975, 40.764],
[-73.975, 40.768],
[-73.981, 40.768], // 닫기
],
])
const point = turf.point([-73.978, 40.766])
turf.booleanPointInPolygon(point, polygon) // true/false
npm install @turf/turf
Footnotes
-
RFC 7946 — GeoJSON: “The first two elements are longitude and latitude, or easting and northing, precisely in that order” / §3.1.6: “The first and last positions are equivalent, and they MUST contain identical values” ↩