Skip to content

Instantly share code, notes, and snippets.

@aaabdyrahmanov
Last active October 28, 2023 21:37
Show Gist options
  • Save aaabdyrahmanov/473f83eebf79326338d0079c9f0f73b7 to your computer and use it in GitHub Desktop.
Save aaabdyrahmanov/473f83eebf79326338d0079c9f0f73b7 to your computer and use it in GitHub Desktop.
How to convert data into uppercase using Tranform Stream with HTTP Server in NodeJS
const http = require('http');
const { Transform } = require('stream');
const server = http.createServer((req, res) => {
// Create the transform stream:
// OPTION #1
const uppercase1 = new Transform({
decodeStrings: false
});
uppercase1._transform = function (data, enc, cb) {
cb(null, data.toString().toUpperCase());
};
// OPTION #2
const uppercase2 = new Transform({
transform(chunk, encoding, callback) {
this.push(chunk.toString().toUpperCase());
callback();
}
});
// OPTION #3
const { StringDecoder } = require('string_decoder')
class UppercaseCharacters extends Transform {
constructor(options) {
super (options)
// The stream will have Buffer chunks. The
// decoder converts these to String instances.
this._decoder = new StringDecoder('utf-8')
}
_transform (chunk, encoding, callback) {
// Convert the Buffer chunks to String.
if (encoding === 'buffer') {
chunk = this._decoder.write(chunk)
}
// Exit on CTRL + C.
if (chunk === '\u0003') {
process.exit()
}
// Uppercase lowercase letters.
if (chunk >= 'a' && chunk <= 'z') {
chunk = chunk.toUpperCase()
}
// Pass the chunk on.
callback(null, chunk)
}
}
const uppercase3 = new UppercaseCharacters()
// OPTION #1
req.pipe(uppercase1).pipe(res);
// OPTION #2
// req.pipe(uppercase2).pipe(res);
// OPTION #3
// req.pipe(uppercase3).pipe(res);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment