inject-body

1.0.2 • Public • Published

inject-body

npm version Build Status Coverage Status

Inject contents into the HTML <body> tag of an HTTP response

const {createServer} = require('http');
const fetch = require('node-fetch');
const injectBody = require('inject-body');
 
createServer((req, res) => {
  injectBody(res, Buffer.from('Hello '));
 
  res.setHeader('content-type', 'text/html');
  res.end('<html><body>World</body></html>');
}).listen(3000, async () => {
  return (await fetch('http://localhost:3000')).text(); //=> '<html><body>Hello, World</body></html>'
});

Installation

Use npm.

npm install inject-body

API

const injectBody = require('inject-body');

injectBody(response, contents)

response: http.ServerResponse
contents: Buffer

If the media type of the response is text/html, it inserts a given contents into the response body as the first child of <body> tag, with increasing the value of Content-Length header if necessary.

const {createServer} = require('http');
const fetch = require('node-fetch');
const injectBody = require('inject-body');
 
const html = Buffer.from('<html><body><h2>Hi</h2></body></html>');
const inserted = Buffer.from('<h1>🏄‍</h1>');
 
createServer((req, res) => {
  injectBody(res, inserted);
 
  res.setHeader('content-type', 'text/html');
  res.setHeader('content-length', 37/* Buffer.byteLength(html) */);
  res.end(html);
}).listen(3000, async () => {
  const response = await fetch('http://localhost:3000');
 
  Number(response.headers.get('content-length'));
  //=> 53, Buffer.byteLength(html) + Buffer.byteLength(inserted)
 
  return response.text(); //=> '<html><body><h1>🏄‍</h1><h2>Hi</h2></body></html>'
});

If the media type is not text/html or the response body has no <body> tag, it does nothing.

class injectBody.InjectBody(contents)

contents: Buffer
Return: Function

Create a new injectBody function with the fixed contents argument. Use this class if a server will inject the same contents into every HTML response many times.

const {InjectBody} = require('inject-body');
 
const injectStyle = new InjectBody(Buffer.from('<style>body {color: red}</style>'));

License

ISC License © 2018 Shinnosuke Watanabe

Package Sidebar

Install

npm i inject-body

Weekly Downloads

2

Version

1.0.2

License

ISC

Unpacked Size

11 kB

Total Files

4

Last publish

Collaborators

  • shinnn