LoginSignup
2
1

More than 3 years have passed since last update.

Node.jsでDeprecationWarningを出さずにencodeとdecode

Posted at

環境

$ node --version
v12.16.1

経緯

Buffer を使って、encodeしたかった時にDeprecationWarningが出てしまったため対処
encode自体は問題なくできるが、nodejsのドキュメント的には対応した方が良さそう

test.js
const before = 'hogehoge'  // これをbase64でencodeしたい
const buffer = new Buffor(before)
const after = buffer.toString('base64')
console.log(after)

$ node test.js
aG9nZWhvZ2U=
(node:631) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

やったこと

new Bufferの書き方を修正した

test.js
const before = 'hogehoge'
const after = Buffer.from(before).toString("base64");
console.log(after)

↓ 無事エラーが消えた!

$ node test.js
aG9nZWhvZ2U=

ちなみに、decodeはこちら

test.js
const after = 'aG9nZWhvZ2U'
const before = Buffer.from(after, 'base64').toString()
console.log(before)

$ node test.js
hogehoge

参考

2
1
0

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
2
1