JavaScript

Node.js CODE TIPS

ファイル読み込み

テキストファイルの読み込みである場合'utf-8'のようにエンコーディングを指定する。

const fs = require('fs');

// sync
const text = fs.readFileSync('./input.txt', 'utf8');

// async
fs.readFile('./input.txt', 'utf8', function(err, text) {
  if (err) throw err;
  console.log(text);
});

ファイル書き込み

ファイル書き込み(上書き)

require('fs').writeFile('out.txt', 'content', (e)=>{});

1列読み込み

sample.txt
red
blue
green
yellow
const fs = require('fs');
const content = fs.readFileSync('sample.txt').toString();
const colors = content.trim().split('\n');
//=> [ 'red', 'blue', 'green', 'yellow' ]

CSV読み込み

sample.csv
fruit
apple
#banana
orange
lemon
function readCsvSync
function readCsvSync(filename, options) {
  const fs = require('fs');
  const parse = require('csv-parse/lib/sync');
  const content = fs.readFileSync(filename).toString();
  return parse(content, options);
}
use header
const options = { columns: true, comment: '#' };
const records = readCsvSync('sample.csv', options);
/*
[ { fruit: 'apple' },
  { fruit: 'orange' },
  { fruit: 'lemon' } ]
*/
indicate columns
const options = { columns: ['id'], comment: '#' };
const records = readCsvSync('sample.csv', options);
/*
[ { id: 'fruit' },
  { id: 'apple' },
  { id: 'orange' },
  { id: 'lemon' } ]
*/

glob

npm i glob
const glob = require('glob');

glob.sync("**/*.js", options, function(er, files) {
  // files is an array of filenames.
});

URL Path Join

url.resolve(from, to) を使用する。 よくある join による連結ではなく、現在地と行き先を渡す。 from で指定された URL を現在地として to という行き先を命令された場合に 結局どこに行くのかを解明した結果を返す。 from は http:// で開始する必要はない。 逆に to が http:// から始まる URL でもよい。 それは外部サイトに移動する時と同じ挙動と言える。

url.resolve('/japan/tokyo/shibuya', 'ebisu')
//=> '/japan/tokyo/ebisu'
url.resolve('http://world.com', 'japan')
//=> 'http://world.com/japan'
url.resolve('http://world.com/japan/tokyo/', '../osaka/')
//=> 'http://world.com/japan/osaka/'
url.resolve('http://world.com/japan/tokyo/', '/america/new-york')
//=> 'http://world.com/america/new-york'
url.resolve('http://world.com', 'https://google.com')
//=> 'https://google.com/'

tktk