@ukab/sbody
TypeScript icon, indicating that this package has built-in type declarations

0.2.2 • Public • Published

Stream Receiver

The library is compitable with both ESM and CommonJS. You can use this package with any framework or even with NodeJS native http module.

Usage

From client side use the following headers

Content-Transfer-Encoding: binary

Content-Disposition: attachment; filename="[file name with extension]"
Example: Content-Disposition: attachment; filename="image.jpeg"

Content-Type: [file mime]
Example: Content-Type: image/jpeg

with native http module

const { createServer } = require('http');

const sbody = require('@ukab/sbody');

const streamReceiver = sbody();

createServer(async (req, res) => {
  const ctx = { req, res };

  await streamReceiver(ctx);

  res.end(JSON.stringify({
    data: { file: ctx.file },
  }));

}).listen(3000);

with koa

app.use(async (ctx, next) => {
   await streamReceiver(ctx);
   await next();
});

with express

app.use((req, res, next) => {
  const ctx = { req, res };

   streamReceiver(ctx)
    .then(() => {
      next();
    }).catch(next);
});

Options

All options are optional

interface IOptions {
  pipe: boolean // should auto pipe request or not, default true
  storagePath: string // default os temp dir
  maxBytes: number // default 10e+6
  bufferBytes: number // default 1024
  filename: (ext: string) => string // default upload_<random hex id>.ext
  pathResolver(storagePath: string, filename: string): string // default path.resolve(storagePath, filename)
  writer: (file: IFile, req: IncomingMessage) => Promise<Stream> // default fs.createWriteStream(file.path)
  shouldParseRequest: (req: IncomingMessage) => boolean // default if content-disposition header present with attachment init
}
const streamReceiver = sbody({
  ...options
});

File

Below is the file that context holds

interface IFile {
  name: string
  originalName: string
  type: string
  extension: string
  path: string
  size: number
  buffer: Buffer
}

Package Sidebar

Install

npm i @ukab/sbody

Weekly Downloads

1

Version

0.2.2

License

UNLICENSED

Unpacked Size

20.7 kB

Total Files

14

Last publish

Collaborators

  • bitnbytes