Skip to content
/ charset Public

use iconv-lite to encode the body and set charset to content-type

License

Notifications You must be signed in to change notification settings

koajs/charset

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

35 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NPM version build status Coveralls David deps node version Gittip

Use iconv-lite to encode the body and set charset to content-type.

Install

# npm ..
npm i koa-charset
# yarn ..
yarn add koa-charset

Usage

const Koa = require('koa');
const charset = require('koa-charset');

const app = new Koa();

app.use(charset());
app.use(function (ctx) {
  ctx.body = '你好';
  ctx.type = 'text/html; charset=gbk';
});

app.listen(3000);

Options

  • charset: set global charset by options.charset

Manually turning charset on and off

You can set ctx.charset to cover the global charset.

app.use(function (ctx) {
  ctx.charset = 'gb2312';
  ctx.body = '你好';
});

You can disable charset by ctx.charset = false.

app.use(function (ctx) {
  ctx.charset = false;
  ctx.body = 'hello';
});

also this module will get the charset from Content-Type, so you can just use koa-charset, then this middleware will automatically re-encode the body only if the charset is not utf8.

const app = new Koa();
app.use(charset());
app.use(function () {
  const charset = ctx.acceptsCharsets('utf8', 'gbk') || 'utf8';
  ctx.vary('accept-charset');
  ctx.type = `text/plain; charset=${charset}`;
  ctx.body = 'something';
});

License

MIT

About

use iconv-lite to encode the body and set charset to content-type

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •