/r/node
Hi!
I want to create a node/express.js server that generates pdf files from react components with react-pdf and typescript.
I have tried to create the app like this but the server won't start.
// server.ts
import express, { Request, Response } from "express";
import React from "react";
import { renderToStream } from "@react-pdf/renderer";
import Report from "./components/Report";
const app = express();
app.use(express.json());
app.post("/generate-report", async (req: Request, res: Response) => {
const { title, content } = req.body;
const pdfStream = await renderToStream(
<Report title={title} content={content} />
);
res.setHeader("Content-Type", "application/pdf");
pdfStream.pipe(res);
});
app.listen(3000, () => console.log("Server running on http://localhost:3000"));
// error
npx ts-node src/server.ts
C:\projects\app-reporting\node_modules\ts-node\src\index.ts:859
return new TSError(diagnosticText, diagnosticCodes, diagnostics);
^
TSError: ⨯ Unable to compile TypeScript:
src/server.ts:12:19 - error TS2554: Expected 1 arguments, but got 3.
12 <Report title={title} content={content} />
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/server.ts:12:27 - error TS2588: Cannot assign to 'content' because it is a constant.
12 <Report title={title} content={content} />
~~~~~~~
src/server.ts:12:35 - error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
12 <Report title={title} content={content} />
~~~~~~~~~
src/server.ts:12:13 - error TS1005: '>' expected.
12 <Report title={title} content={content} />
~~~~~
src/server.ts:12:18 - error TS1005: ',' expected.
12 <Report title={title} content={content} />
~
src/server.ts:12:27 - error TS1005: ',' expected.
12 <Report title={title} content={content} />
~~~~~~~
src/server.ts:12:46 - error TS1109: Expression expected.
12 <Report title={title} content={content} />
~
src/server.ts:13:3 - error TS1109: Expression expected.
13 );
~
at createTSError (C:\projects\app-reporting\node_modules\ts-node\src\index.ts:859:12)
at reportTSError (C:\projects\app-reporting\node_modules\ts-node\src\index.ts:863:19)
at getOutput (C:\projects\app-reporting\node_modules\ts-node\src\index.ts:1077:36)
at Object.compile (C:\projects\app-reporting\node_modules\ts-node\src\index.ts:1433:41)
at Module.m._compile (C:\projects\app-reporting\node_modules\ts-node\src\index.ts:1617:30)
at Module._extensions..js (node:internal/modules/cjs/loader:1426:10)
at Object.require.extensions.<computed> [as .ts] (C:\projects\app-reporting\node_modules\ts-node\src\index.ts:1621:12)
at Module.load (node:internal/modules/cjs/loader:1205:32)
at Function.Module._load (node:internal/modules/cjs/loader:1021:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:142:12) {
diagnosticCodes: [
2554, 2588, 2362,
1005, 1005, 1005,
1109, 1109
]
}
// Report.tsx
import React from "react";
import { Document, Page, Text, View, StyleSheet } from "@react-pdf/renderer";
const styles = StyleSheet.create({
page: {
flexDirection: "column",
backgroundColor: "#E4E4E4",
},
section: {
margin: 10,
padding: 10,
flexGrow: 1,
},
});
interface ReportProps {
title: string;
content: string;
}
const Report: React.FC<ReportProps> = ({ title, content }) => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>{title}</Text>
</View>
<View style={styles.section}>
<Text>{content}</Text>
</View>
</Page>
</Document>
);
export default Report;
Hello, i want to learn a backend framework that supports functional/reactive programming(rxjs etc).(i come from clojure).
I care only for the backend and microservices support.
I want it to be data-oriented, like JSON for data and functions to process it, ideally in a chaining way, like rxjs does. Not OOP state and DTO's etc.
data(JSON)+chained async functions with rxjs ideally, code to be like a pipeline of data tranformations.
I saw many NestJS, Fastify, Express, Elysia etc the most functional to me was Elysia, NestJS uses rxjs but its like spring full of OOP, i don't like those, does anyone knows if i can use NestJS in functional way?
Help me if you can to pick one and start learning it, i guess many JS people like functional and reactive programming. Also i want a popular one, to be able to get a Job with using it, for example i saw Marble.js
but sadly its not popular i think.
I am working on a B2C startup and need to design the backend for a website and mobile apps supporting a chat application. The platform will incorporate AI/ML models to analyze chats and user inputs, alongside a notification system for users. My initial idea is to separate the backend and AI services. Should I use Python for both the backend and AI components, or would it be better to leverage Nest.js for the backend, while using Python for AI?
I just spun up a new ubuntu server vm earlier today and tried to run a small web server that I currently have running on a ubuntu desktop vm and I'm using vhost to do subdomains in the web server. This works in the ubuntu desktop vm, but when I try the same thing in the ubuntu server vm I can still ping the server, but I always get Cannot GET /. When I remove the vhost portion and just route through express it seems to work fine. Does anyone know what would cause this issue?
Hello everybody,
I am working on a React application with NodeJs and MongoDB in the backend. The homepage contains around a dozen cards with totals of each status of order, clicking on each card refreshes a view on the same page with the list of orders. The way it was implemented loads information from all the cards in order to populate the total label on each card, so when loading the home page there's at least a dozen requests being made to populate the cards and the tables, even though the user will never click on all of them, this is something planned to change.
Besides that, my team as considering extracting the cards logic in a service/worker and a new MongoDB collection for each type of order status (I honestly didn't like it), so when an order is saved, the frontend will post a message to a queue that will be consumed by the worker, this worker will validate the business logic and either persist it into its status collection or ignore the message.
For the cards refactoring, they should hit an endpoint in this new service/worker which will query the DB and provide the orders for that user.
I am a junior developer and wasn't able to add much to the planning meetings and don't have enough experience to imagine a different design for this system so I have a couple of questions for this community:
- Has any of you worked on something similar? How would you design this refactor considering the UI has had some issues with performance loading all this info?
- Would you consider something like GraphQL or another protocol to improve the performance?
- Is the MongoDB collection for each status something that makes sense? I didn't like the idea of replicating information but I don't know how to prove my point that it could end up creating more problems.
Cheers!
If i alter the table and migrate new change already existing datas are deleted with Prisma, Type ORM.
How to solve this issue?
Hi everyone, I was planning to do a startup using nest js in backend, my only concern is, it's not backed up by a big corp and on github I see most of the commits by the founder himself. So just wanted to ask is it good for long term support or longevity as after 5 or 6 years I do not want to hear that nest is no longer available something like that ?
Hi guys, I'm having problems with my response.end. the controller is entering catch. and I'm getting this error: SyntaxError: Failed to execute 'json' on 'Response': Unexpected end of JSON input
Front-end
async function handleSend(data: UserSchema) {
try {
const response = await fetch("http://localhost:3000/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
console.log(response)
const result = await response.json()
console.log(result)
} catch (err) {
console.log(err)
}
}
LoginController
request.on("end", async () => {
try {
const userBodySchema = z.object({
username: z.string().min(5),
email: z.string().email(),
password: z.string().min(6),
})
const bodyData = userBodySchema.parse(JSON.parse(body))
console.log(bodyData)
response.statusCode = 200
response.setHeader("Content-Type", "application/json");
response.end(JSON.stringify(bodyData));
} catch (err) {
console.log('entrou no catch')
response.statusCode = 400
if (err instanceof Error) {
response.end(
JSON.stringify({
"bilada: ": err.message
})
)
} else {
response.end(
JSON.stringify({
error: "Invalid request body"
})
)
}
}
})
I'm getting this error: SyntaxError: Failed to execute 'json' on 'Response': Unexpected end of JSON input
We have an API that returns a script.js which is calculated on the fly. However, this script.js depend on other files that are prepended before returning them as a response.
What tool can I use to do this merging? I would like to keep it as simple as possible, not sure if using something like webpack on the server is what we want.
Edit: Will explain the use-case since people is asking. We provide a checkout script to an ecommerce platform that evaluates the code from their side. This script has dynamic behaviour such as enabling functionality depending on the merchants configuration (captcha, fingerprinting, etc etc). This is also cached but refreshed after a few hours. We prefer this approach so we can roll changes to the checkout safely.
We currently run Flyway programatically in our Java applications on startup to migrate our database. Is there something similar in the Node.js world? We prefer not to use a CLI tool.
Flyway works by keeping track of migrations with its own table. Calling the `migrate` method simply looks at the SQL scripts we have and checks the latest in its table. If there are newer scripts, it will apply them on the database and update its table.
We are probably going to use Drizzle, which doesn't seem to support this.
Thanks!
So I've spoken to company that claims that they can track which companies have visited my website based on the visitor IP address - Is this really something that is still possible? and if, then how the hell, i would really love to know also how accurate are they?
I do know that there's services like Clearbit that offer this but they got acquired by Hubspot and now it cost a LARGE amount of money to integrate with them. So if you have experience with other service that can provide these kinda enrichments
The reason im posting this here is because i would like to build an alternative to these at the fraction of the price and code it in Node
As I understand, node's GC works across multiple threads. Some of the work is offloaded from the main thread to reduce GC pauses.
So I am confused what the performanceEntry.detail.duration
represents when I am observing the gc
? Is it the amount of time that the GC pauses the main thread or the total time across all threads uswd by e.g. the major gc?
My service is reporting major GC p50 of 50ms, so I am not sure, if I should be worried or not..
I use native fetch in node so mocking these calls in testing has been challenging. I finally now have a way of dealing with it using MSW. No more axios or pseudo fetch libraries. I'm all fetch now and I'm quite happy with the results. I can mock any http call now. The only hitch is if you use stripe, you gotta do it like this:
const {Stripe} = require('stripe') // Import the Stripe constructor
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
httpClient: Stripe.createFetchHttpClient(), // Switch to fetch-based client
apiVersion: '2024-10-28.acacia',
})
or stripe just hangs in tests.
Code example: -
const createSHA512Hash = (v: string): string => crypto.createHash('sha512').update(v).digest('hex')
const createSHA512Hash = (v: string): string => crypto.createHash('sha512').update(v).digest('base64')
The code examples I have seen online have always shown a digest of hex
. Base64
is shorter than hex
and both should be equally secure as it is an simply encoding of the output from SHA.
Shorter is always better when it doesn't compromise anything.
Right so I've been researching and playing with this idea for a couple of days
I initially wanted to use RTMP because that's what big streaming platforms use apparently
However it is not supported by browsers, it's intended to be used with something like OBS directly to my server, where I would take the video data and transcode it into HLS or DASH, then store it in some CDN
So now that I've found out RTMP is off the table (I want the user to stream directly from the browser) I'm thinking of sending video data from the browser to the server in Buffer format via websockets, continuously while the stream is running
And on the server I would take that data and transcode it using ffmpeg to DASH/HLS as I mentioned before, then store it in a media server
Is this a reasonable approach ?
(WebRTC is off the table because I'm gonna have a large number of users and peer to peer is not gonna work)
I am a mobile developer using React Native. I have knowledge in back-end development, but not so in-depth. I know things like: AWS, Nest, Express, etc. I want to understand it in-depth and specialize on a backend framework as I have specialized on React Native.
I have already asked this in StackOverflow but I'm not sure if that was the right place, so:
I have a typical NestJS application and I integrated BullMQ to make use of queues for the following cases:
I came across this and from what I understood, I should be going for a separate Node process or a worker thread only if there are heavy synchronous computations (parallelism). Since all of my functionalities are asynchronous and there are no "heavy computation" (no stuff like image compression or video conversion going on), should I still go for a separate process/worker? I assume mine is instead a case of concurrency?
Also, I'm confused as to what's considered synchronous or asynchronous: let's say I have a large list of user items that I loop through and perform tasks like triggering emails to each item through Promise.map
. Is that async (concurrent) or sync (parallel)? I ask this because if I had to implement a heavy computation like image processing and wrap it in an async scope, it would still block the main thread. So would my case of looping also block the thread then?
Hey NodeJs Experts,
I'm really hoping someone here can lend me a hand. I'm working on a live sports app that currently uses MQTT to broadcast live scores. We're now looking to implement a group chat feature that allows users to discuss the match while it's in progress. I initially chose Ejabberd to set up an XMPP server and made decent progress, but I've hit a roadblock. I can't seem to retrieve older messages in group chats (rooms). I'm suspecting it's either an issue with MySQL or a problem with the MAM (Message Archive Management) mechanism for MUC. I've been stuck on this for a while now and it's starting to get frustrating. Ideally, I'd love to get some help resolving this Ejabberd issue. Has anyone else experienced similar problems with message retrieval or MAM? Any pointers would be greatly appreciated! Alternatively, I'm open to exploring other solutions. Could someone provide some guidance on implementing group chat using websockets? I'm particularly interested in how to efficiently handle group functionality and message persistence. Any help or advice would be a lifesaver. Thanks in advance for your time and expertise!
I'm developing a Node.js application using TypeScript and Express and have set up Pino as my logger.
The issue is that my logger doesn't output to the console or the log file. It doesn't seem to be triggered even when I attempt to close the server. Here's the process handler for more context:
import { MongoRepository } from '@repositories/index'
import { container } from '@container/index'
import types from '@inversifyTypes/types'
import { messages } from '@shared/index'
import logger from '@logging/logger'
import { Server } from 'http'
const processHandler = (server: Server): void => {
const exit = (signal: string): void => {
console.log(`Received signal ${signal}. Closing resources...`)
logger.info(`Received signal ${signal}. Closing resources...`)
server.close(async () => {
console.log('Closing MongoDB connection...')
logger.info('Closing MongoDB connection...')
const mongoRepository = container.get<MongoRepository>(types.MongoRepository)
await mongoRepository.disconnect(false, () => {
logger.info(messages.DISCONNECTED)
process.exit(0)
})
})
}
// Handle SIGINT (Ctrl+C in the terminal)
process.on('SIGINT', () => exit('SIGINT'))
// Handle SIGTERM (termination signal sent)
process.on('SIGTERM', () => exit('SIGTERM'))
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
logger.error({ error }, 'Uncaught exception detected')
exit('uncaughtException')
})
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
logger.error({ promise, reason }, 'Unhandled promise rejection detected')
exit('unhandledRejection')
})
}
export default processHandler
What could be going wrong here? Why aren't the logger's outputs showing in the console or the log file? How can I ensure it captures the shutdown process correctly?
Hello, I am learning frontend from scrimba and I really like their layout of learning the concept first and practicing it straight away. I am almost done with react and js and was trying to find some similar platform to learn backend programming but couldn't find anything similar to scrimba, most of the tutorials are video orientated or just plain text. Could you please recommened me some good tutorials?
I’m not sure the proper process. I’ve been looking at two different ways to get the file to the server: by breaking up the file into chunks and then sending a bunch of requests to the server, one for each chunk.
OR, breaking up the file into chunks, and then sending them all to the server in one request.
After that, then what? Do I write the file to a folder on the server, and then send that to the cloud? And if I write the file to the server, do I use a stream to get it to the cloud?
Or do I take the file from the front end and pass the chunks straight into a stream?
I am a full stack developer and have been building apps and websites for the last three years. I write pretty good code with class based mvc architecture, but I wanna know what things I can do better. I have attached a screenshot of my current file structure.
Things I do:
If you guys have any template repo that I can take inspirations from it will be great. Let me know what I can improve.
I built an app with FlutterFlow and Supabase.
I am going back and adding an API to act as the middleman instead of directly connecting frontend to backend. I am not a great programmer but I can figure it out. My tentative plan is Express + Typescript + Drizzle ORM + Supabase (auth/DB). Any words of caution or other recommendations you would have? The indecision is killing me. I just need to decide and start building, but I don't want to build out and then realize I should have used something else.