Skip to content

Instantly share code, notes, and snippets.

@7cc
Last active March 19, 2019 17:13
Show Gist options
  • Select an option

  • Save 7cc/d25ce6ee5be9a8517271d71ca4523a53 to your computer and use it in GitHub Desktop.

Select an option

Save 7cc/d25ce6ee5be9a8517271d71ca4523a53 to your computer and use it in GitHub Desktop.

node one liner

  • 実用的でない
  • windowsだとsjis問題に悩まされる

これをやりたい

echo "こんにちは" | perl -pe 's/にちは/ばんは/'

基本形

node
  -p = print
  -e = eval
node -p "'こんにちは'.replace('にちは', 'ばんは')"

node -p "process.argv[1]" `echo hello`

node -p "'こんにちは'.replace('にちは', 'ばんは')"
node -p "arg=process.argv; arg[1].replace(arg[2], arg[3])" `echo こんにちは にちは ばんは`
node -p "arg=process.argv; arg[1].replace(arg[2], arg[3])" 'こんにちは' 'にちは' 'ばんは'

pipe

# stdin, nonly one param
echo 'console.log({a:1, b:2})' | node.exe -
echo '({a:1, b:2})' | node.exe -p
echo '({a:1, b:2})' | xargs -0 -i node.exe -pe '({})'
echo '"こんにちは".replace("にちは", "ばんは")' | node.exe -p
# パイプ処理できないので&&を使う
echo "こんにちは" && node -p 'process.argv[1].replace("にちは", "ばんは")' $_
echo "こんにちは にちは ばんは" && node -p 'process.argv[1].replace(process.argv[2], process.argv[3])' $_
# パイプ処理できないのでfs.readFileSyncを使う
echo '({a:1, b:2})' | node.exe -p "fs.readFileSync(0, 'utf8')"
echo 'こんにちは' | node.exe -p "fs.readFileSync(0, 'utf8').replace('にちは', 'ばんは')"
echo 'こんにちは' | node.exe -p "fs.readFileSync(0, 'utf8').replace(process.argv[1], process.argv[2])" 'にちは' 'ばんは'
curl 'https://jsonplaceholder.typicode.com/todos/1' | node.exe -p "JSON.parse(fs.readFileSync(0, 'utf8'))"
curl 'https://jsonplaceholder.typicode.com/todos/1' | xargs -0 -i node.exe -p '({})'

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment