Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update body parsing and file streaming exemples #1128

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions examples/FileStreaming.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// This is an example of streaming files

const uWS = require('../dist/uws.js');
const fs = require('fs');

const port = 9001;
const bigFileName = 'absolutPathTo/bigVideo.mp3';
const bigFileSize = fs.statSync(bigFileName).size;
console.log('Video size is: '+ bigFileSize +' bytes');

// Stream data to res
/** @param {import('node:Stream').Readable} readStream */
const streamData = (res, readStream, totalSize, onFinished) => {
let chunkBuffer; // Actual chunk being streamed
let totalOffset = 0; // Actual chunk offset
const sendChunkBuffer = () => {
const [ok, done] = res.tryEnd(chunkBuffer, totalSize);
if (done) {
// Streaming finished
readStream.destroy();
onFinished();
} else if (ok) {
// Chunk send success
totalOffset += chunkBuffer.length;
// Resume stream if it was paused
readStream.resume();
} else {
// Chunk send failed (client backpressure)
// onWritable will be called once client ready to receive new chunk
// Pause stream
readStream.pause();
}
return ok;
};

// Attach onAborted handler because streaming is async
res.onAborted(() => {
readStream.destroy();
onFinished();
});

// Register onWritable callback
// Will be called to drain client backpressure
res.onWritable((offset) => {
const offsetDiff = offset - totalOffset;
if (offsetDiff) {
// If start of the chunk was successfully sent
// We only send the missing part
chunkBuffer = chunkBuffer.subarray(offsetDiff);
totalOffset = offset;
}
// Always return if resend was successful or not
return sendChunkBuffer();
});

// Register callback for stream events
readStream.on('error', (err) => {
console.log('Error reading file: '+ err);
// res.close calls onAborted callback
res.close();
}).on('data', (newChunkBuffer) => {
chunkBuffer = newChunkBuffer;
// Cork before sending new chunk
res.cork(sendChunkBuffer);
});
};

let lastStreamIndex = 0;
let openStreams = 0;

const app = uWS./*SSL*/App({
key_file_name: 'misc/key.pem',
cert_file_name: 'misc/cert.pem',
passphrase: '1234'
}).get('/bigFile', (res, req) => {
const streamIndex = ++ lastStreamIndex;
console.log('Stream ('+ streamIndex +') was opened, openStreams: '+ (++ openStreams));
res.writeHeader('Content-Type', 'video/mpeg');
// Create read stream with fs.createReadStream
streamData(res, fs.createReadStream(bigFileName), bigFileSize, () => {
// On streaming finished (success/error/onAborted)
console.log('Stream ('+ streamIndex +') was closed, openStreams: '+ (-- openStreams));
});

}).get('/smallFile', (res, req) => {
// !! Use this only for small files !!
// May cause server backpressure and bad performance
// For bigger files you have to use streaming
try {
const fileBuffer = fs.readFileSync('absolutPathTo/smallData.json');
res.writeHeader('Content-Type', 'application/json').end(fileBuffer);
} catch (err) {
console.log('Error reading file: '+ err);
res.writeStatus('500 Internal Server Error').end();
}
}).listen(port, (token) => {
if (token) {
console.log('Listening to port ' + port);
} else {
console.log('Failed to listen to port ' + port);
}
});
72 changes: 0 additions & 72 deletions examples/JsonPost.js

This file was deleted.

89 changes: 89 additions & 0 deletions examples/ParseJsonOrFormBody.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Simple example of parsing JSON body or URL-encoded form

const querystring = require('node:querystring');
const uWS = require('../dist/uws.js');
const port = 9001;

// Helper function for parsing JSON body
const parseJSONBody = (res, callback) => {
let buffer = Buffer.alloc(0);
// Register data callback
res.onData((ab, isLast) => {
buffer = Buffer.concat([buffer, Buffer.from(ab)]);
if (isLast) {
let parsedJson;
try { parsedJson = JSON.parse(buffer.toString()); }
catch { parsedJson = null; }
callback(parsedJson);
}
});
};

// Helper function for parsing URL-encoded form body
const parseFormBody = (res, callback) => {
let buffer = Buffer.alloc(0);
// Register data callback
res.onData((ab, isLast) => {
buffer = Buffer.concat([buffer, Buffer.from(ab)]);
if (isLast) {
let parsedForm;
try { parsedForm = querystring.parse(buffer.toString()); }
catch { parsedForm = null; }
callback(parsedForm);
}
});
};

const app = uWS./*SSL*/App({
key_file_name: 'misc/key.pem',
cert_file_name: 'misc/cert.pem',
passphrase: '1234'
}).get('/jsonAPI', (res, req) => {
// Attach onAborted handler because body parsing is async
res.onAborted(() => {
res.aborted = true;
});

parseJSONBody(res, (object) => {
if (res.aborted) return;
if (!object) {
console.log('Invalid JSON or no data at all!');
res.cork(() => { // Cork because async
res.writeStatus('400 Bad Request').end();
});
} else {
console.log('Valid JSON: ');
console.log(object);
res.cork(() => {
res.end('Thanks for this json!');
});
}
});
}).post('/formPost', (res, req) => {
// Attach onAborted handler because body parsing is async
res.onAborted(() => {
res.aborted = true;
});

parseFormBody(res, (form) => {
if (res.aborted) return;
if (!form || !form.myData) {
console.log('Invalid form body or no data at all!');
res.cork(() => { // Cork because async
res.end('Invalid form body');
});
} else {
console.log('Valid form body: ');
console.log(form);
res.cork(() => {
res.end('Thanks for your data!');
});
}
});
}).listen(port, (token) => {
if (token) {
console.log('Listening to port ' + port);
} else {
console.log('Failed to listen to port ' + port);
}
});
115 changes: 0 additions & 115 deletions examples/VideoStreamer.js

This file was deleted.

Loading