Comments (5)
You can completely avoid the through stream, because it's jut adding overhead. You are not listening to any of the backpressure event. BTW, you should use through2, and read https://nodejs.org/en/docs/guides/backpressuring-in-streams/.
In your example, you should reuse the fastJson instance, otherwise it will be very very slow.
from fast-json-stringify.
@AutoSponge that would be handy, but it will change the logic heavily. Supporting streams means that we need to support backpressure, otherwise it is somewhat useless. In order to support backpressure, we need to generate the object in chunks, and to maintain a state of the object while we are doing that.
I think it's extremely complicated, and probably very expensive.
If you would like to lift some code from here in another OSS project, I'll be very happy to review that, but I feel it's too much for fast-json-stringify.
from fast-json-stringify.
This is what I came up with, not sure if it's naive:
const fastify = require('fastify')()
const through = require('through')
const fastJson = require('fast-json-stringify')
const schema = {
out: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
const everyoneInTheWorld = [
'Olivia', 'Ethan', 'Isabella', 'Liam', 'Ava', 'Mason', 'Lily', 'Noah'
]
const jsonStream = (schema) => {
let stream
let first = true
let anyData = false
stream = through((data) => {
let json
anyData = true
try {
json = fastJson(schema)(data)
} catch (err) {
return stream.emit('error', err)
}
if (first) {
first = false;
stream.queue(`[\n${json}`)
} else {
stream.queue(`\n,\n${json}`)
}
},
(data) => {
if (!anyData)
stream.queue('[\n')
stream.queue('\n]\n')
stream.queue(null)
})
return stream
}
// skip the output schema since it's a collection endpoint
fastify.get('/', function (req, reply) {
reply.header('Content-Type', 'application/stream+json')
const stream = jsonStream(schema.out)
stream.on('data', (data) => reply.res.write(data))
stream.on('end', () => reply.res.end())
let i = 0
// use a pump just to prove it's a stream in the console: curl http://localhost:4000/ -v
let pump = setInterval(() => {
const hello = everyoneInTheWorld[i++]
if (i === everyoneInTheWorld.length) {
clearInterval(pump)
stream.end({ hello })
} else {
stream.write({ hello })
}
}, 100)
})
fastify.listen(4000)
from fast-json-stringify.
That won't work as you expect. It will generate all the chunks and add them for sending. You will be allocating the same amount of memory, and adding the stream overhead.
from fast-json-stringify.
I appreciate the quick reply, but I'm not sure I understand the issue. If it's the backpressure/flushing issues with .write
, then adding the callback to .write
should take that away (see below). But if it's something else, I'm not sure how to observe it.
fastify.get('/', function (req, reply) {
let i = 0
const pump = () => {
const hello = everyoneInTheWorld[i++]
if (i === everyoneInTheWorld.length) {
stream.end({ hello })
} else {
stream.write({ hello })
}
}
reply.header('Content-Type', 'application/stream+json')
const stream = jsonStream(schema.out)
stream.on('data', (data) => reply.res.write(data, pump))
stream.on('end', () => reply.res.end())
pump()
})
EDIT: I'm keeping the current implementation in a gist if anyone wants to follow along or provide feedback.
from fast-json-stringify.
Related Issues (20)
- Get Test Coverage to 100%
- bigger function body => perf hit HOT 3
- missing options in types HOT 5
- Broken error message for missing required property HOT 6
- TypeCoercion like ajv HOT 5
- Use fast-json-escape for string serialization HOT 2
- oneOf schemas not matching when an object has a custom toJSON() method HOT 1
- standalone mode can't be devDependancy HOT 5
- Support TypedArrays HOT 1
- Support of JSON Schema draft 2020-12 HOT 4
- Breaking the typia performance advantage HOT 4
- Schema serialization of anyOf/oneOf properties are parsed incorrectly HOT 1
- Recursive validation schema compiles but fails at runtime HOT 5
- error while resolving nested objects HOT 2
- `node:crypto` issues in Next.js HOT 7
- Tuple of date-time does not allow Date HOT 3
- Issue with custom keyword not working in fast-json-stringify HOT 11
- Response schema compiler generated validation code does not check for null values on optional object fields HOT 9
- lack of strictSchema in ajv options results in silent typos
- merged schema cache is messed up HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fast-json-stringify.