/r/node

Photograph via //r/node

/r/node

291,974 Subscribers

56

Hi, I created a CLI, that creates a commerce backend and dashboard, that can connect to any database, storage and can run on Node (links in the comments)

9 Comments
2024/12/21
20:17 UTC

0

Fully typed full-stack NextJS template

Per a redditor's request, I have extracted my boilerplate for a full-stack next repo, with typed contracts from the database to the front-end.

The template uses a separate API to unlock next's caching features and circumvent the limitations of next for backend code. It also demonstrates using minimalist express-like patterns but typed (via fastify + zod) instead of relying on maximalist solutions like NestJS.

https://github.com/chriskuech/fullstack-monorepo-template

Let me know your thoughts or if there's anything else you'd like to see.

2 Comments
2024/12/20
19:37 UTC

0

Python wrapper for Typescript lib

I would like to publish a Python library that acts as a wrapper to a Typescript library. I don't want to rewrite the whole library in Python and have to worry about feature parity! What approaches would you reccommend?

1 Comment
2024/12/20
17:13 UTC

3

What Backend Projects Should I Build to Learn Node.js Effectively?

Hey everyone,

I’m getting started with Node.js for backend development and I’m looking for some project ideas that can help me get a better grasp of things like RESTful APIs, working with databases, authentication, and other core concepts.

7 Comments
2024/12/20
16:15 UTC

7

Get backend job without knowing frontend

How possible is for someone beginner to get his first programming job as backend developer without knowing frontend technologies? What is the best study path in this case? For example someone who hates css and don't want to spend time to learn it. PS: I mean backend developer preferably using JavaScript (for example node.js)

36 Comments
2024/12/20
14:20 UTC

0

help me to understant the middleware in next js 15 , i am express js user

1 Comment
2024/12/20
13:21 UTC

0

How to stream shell script output in real-time using Bun, Hono?

I'm trying to create a real-time streaming output of a shell script execution using Bun and Hono. Currently, the output is buffered and only shows up all at once when the script finishes, but I need it to stream in real-time as the script produces output.

Shell Script (deploy-container.sh):

#!/bin/bash
# Script that deploys a container and shows progress
echo "🚀 Starting deployment process..."
echo "  → Deploying Docker container..."
# ... more echo statements and actual deployment logic
echo "✅ Deployed successfully!"

Current Implementation:

(deploy.ts):

import { $ } from "bun";

export const runDeployment = async (
  imageName: string,
  subDomain: string,
  port: number
) => {
  try {
    const res =
      await $`echo ${process.env.SYSTEM_PASSWORD} | sudo -S deploy-container.sh ${imageName} ${subDomain} ${port}`;

    return res.stdout.toString();
  } catch (e) {
    console.error("Error running deployment:", e);
    throw {
      success: false,
      error: e,
    };
  }
};

(index.ts):

import { stream } from "hono/streaming";
import { runDeployment } from "../lib/deploy";

app.post("/deployContainer/:repoName", async (c) => {
  try {
    const repoName = c.req.param("repoName");
    const imageName = `${repoName}:latest`;

    const port = generateRandomPort();
    const subDomain = generateSubdomain(repoName);
    const deployData = runDeployment(imageName, subDomain, port);
    return stream(c, async (clientStream) => {
      const heartbeat = setInterval(async () => {
        try {
          await clientStream.write(" ");
        } catch (err) {
          console.error("Heartbeat failed:", err);
        }
      }, 1000);

      try {
        const res = await deployData;
        clientStream.writeln(res);
      } catch (error) {
        console.error("Error deploying container:", error);
        clientStream.write(`Error deploying container: ${error}\n`);
      } finally {
        clearInterval(heartbeat);
      }
    });
  } catch (e) {
    console.error(e);
    return c.json({ success: false, error: e }, 500);
  }
});

Current Behavior:

  • The script executes successfully
  • Output is collected but only shown all at once when the script completes
  • No real-time streaming of the output

Expected Behavior:

  • Each line of output should appear in real-time as the script produces it
  • Similar to watching the output in a terminal

Any help would be appreciated in getting the output to stream in real-time rather than being buffered until the end.

4 Comments
2024/12/20
12:30 UTC

0

Node.js Developer Seeking New Opportunities

I’m currently looking for a new position as a Node.js developer. I have experience working with React, Node.js, Express, and MongoDB. If you’re hiring or know someone who is, please feel free to DM me or reach out at eveecloud99@gmail.com

0 Comments
2024/12/20
09:16 UTC

0

Node js getting error message from a model to the errorhandler middleware

So the idea is that I have a controller that asks an object in a model to make a document in the database. I have a middleware that triggers after an error is thrown in the controller. But if an error is thrown in the model then it is not caught by the errorHandeler. Now my question is if that is posible to do. I can catch the error in the model and then the server doesn't crash, however I don't know how to give the info about that to the frontend.

Now for some code. I will try to only show the things that matter.

module.exports.post_groep = async (req, res, next) => {
try {
    if (req.body.naam == "") {
        throw Error("Invalid field: naam");
    }
    const groep_id = await Groep.postGroep(db_naam, req.body);
    res.json({ groep: groep_id });
} catch (err) {
    return next(err);
    }
};

Above is the controller, the first step within the process that matters.

const handleErrors = (err) => {
let errors = { naam: "", afdeling: "" };
console.log(err);
if (err.code === 11000) {
    errors.naam = "Naam reeds ingebruik";
    return errors;
}

if (err.message === "Invalid field: naam") {
    errors.naam = "Gelieve het veld naam in te geven";
    }
    return errors;
};

const errHandler = (err, req, res, next) => {
    const errors = handleErrors(err);
    return res.status(400).json({ errors });
};

module.exports = errHandler;

This is obviously the errorhandler. I know for a fact that the thrown error("Invalid field: naam") works. I only need to get the err.code === 11000 to work for now.

class Groep {
static async postGroep(db, obj, next) {
    try {
        /*if (obj.naam == "") {
            throw new Error("Invalid field: naam");
        }*/
        const validate = ajv.compile(schema);
        const valid = validate(obj);
        if (valid) {
            return await connector.queryPoster(db, "groepen", obj, true);
        }
    } catch (err) {
        /*console.error(err.code);*/
        return next(err);
        /*if (err.code == 11000) {
            throw Error("Duplicate field offence");
        }*/
    }
}

As you can see is the connection to the database handled in the model and that works fine. The part commented out within the try block is just me testing it out, however that works only then I would have the same problem as I now have with the duplicate error. the return next(err) within the catch block does not work. I'd need to comment that out and uncomment the line above to make it work without handling the error. The last part also works but it doesn't get handled.

1 Comment
2024/12/20
08:50 UTC

0

How should I install Node JS?

I'm rookie dev trying to install npm, and heard that I can get that by installing node JS. I went to the Node JS, however there are multiple options of downloading.

Should I install v23.5.0 (Current) or v22.12.0 (LTS)

Also, should I install it using fnm, docker, or chocolatey? For some reason it doesn't give me the option to select nvm or brew.

Any help would be appreciated

Edit: Theres also another option for x64, which is the prebuilt download option. Should I do that instead

24 Comments
2024/12/20
00:56 UTC

6

Singleton using Cluster module

Hi everyone. I'm playing with the Cluster module and just tried to "clusterize" my whole Node+Express app. My problem is: how do I create a singleton class (or equivalent) that all the forks can refer to and use? Must I use the messaging system that comes with the Cluster module or is there a different path? Any suggestion, doc or tutorial to read?

13 Comments
2024/12/19
23:28 UTC

0

Looking for reviews of my boilerplate pattern

Hey,

I'm using a feature-based pattern in my boilerplate/starter kit, and I'm looking for reviews to improve it.

As far as I know, the feature-based pattern / folder structure is currently the best option for medium-sized companies.

What do you guys think about that?

https://github.com/ghostlexly/ultimate-expressjs-starter-kit

3 Comments
2024/12/19
22:55 UTC

1

Can't install uWebsockets.js in a docker in node images

I"m able to install and use uWebsockets.js in my mac and it works fine but for some reason It won't work in docker I've tried with node, alpine and slim images, bun, npm, pnpm and yarn, but all of them just create an empty uWebsockets.js directory in node_modules, and I errors because typescript compiler can't find it, I've checked docker files without any imports, it's not there. Not sure why.

I was unable to find much on this while trying to troubleshoot for hours, seems like some issues with binaries not being downloaded for correct platform. but I don't even get any error logs during installation.

This is my docker file

# Use Node.js base image
FROM node:20-slim

# Install build dependencies for uWebSockets.js
RUN apt-get update && \
    apt-get install -y \
    build-essential \
    python3 \
    && rm -rf /var/lib/apt/lists/*

# Create app directory
WORKDIR /usr/src/app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy source code
COPY . .

# Compile TypeScript
RUN npm install -g typescript && \
    tsc

# Expose the WebSocket port
EXPOSE 9001

# Start the server
CMD ["node", "dist/server.js"]

package.json dependency

  "dependencies": {
    "uWebSockets.js": "github:uNetworking/uWebSockets.js#v20.51.0"
  },
4 Comments
2024/12/19
22:20 UTC

80

How to Be Good Backend developer ?? Any advice?🤔

I am a Node.js backend developer trying to get a job in the backend domain. How can I stand out from the crowd? I would love your suggestions, guys. I know Node.js, Express, authentication, authorization, JWT, and MongoDB, and I can build REST APIs. I am currently learning NestJS and can build REST APIs with it as well. What else can I do? I am targeting the next 2-3 months to get a job. I graduated in 2023 and am still jobless. u/srini53168

73 Comments
2024/12/19
13:41 UTC

0

How to res.sendFile using import instead of require

Complete noob here. I am learning node.js following some tutorials and they use this code:

const express = require('express');
const path = require('path');

// Create an Express application
const app = express();

// Define a route to serve the HTML file
app.get('/', (req, res) => {
    // Send the HTML file as the response
    res.sendFile(__dirname + '/index.html');
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is 
        running on port ${PORT}`);
});

But it appears that "require" is getting obsolete in favor of "import" modules. I am trying to do a basic res.sendFile but I am unable to do it.

Could you point me out to a tutorial that will help me with it?

Thanks in advance

11 Comments
2024/12/19
13:39 UTC

6

Need Help Implementing the Status Feature in a WhatsApp Clone

I’m building a WhatsApp clone and working on the status feature, where statuses expire after 24 hours. Continuously checking for expired statuses for every user seems inefficient, even without making frequent API calls. What are some better approaches or backend solutions to handle this efficiently? Any advice or best practices would be greatly appreciated!

16 Comments
2024/12/18
06:23 UTC

7

Why are errors typed « unknown » ?

When you try { ... } catch (error) { ... } this error is always of type unknown. The same for callbacks, when you hane someting like this:

someFunction(aParams, (data,err) => {
  if(err) throw err
  doSomething(data)
})

This err is also typed unknown. Is that because you can throw almost anything is JS ? What's the point of this feature by the way ? Does someone have an example of a situation where throwing something that is not an error was usefull ?

15 Comments
2024/12/18
03:02 UTC

2

Nodejs with activedirectory2, can't get LDAPS working.

LDAP works fine and LDAPS works fine using the ldp tool on the server. Getting ECONNRESET 4077 error in the log file. Using Wireshark the traffic looks fine but of course I can't really tell what's going on because I haven't figured out a way to decrypt the LDAPS traffic yet. Anyone else seen this type of issues? The certificate on the domain controller is public certificate so I think trust is not an issue.

1 Comment
2024/12/17
21:57 UTC

3

How to make my local server's IP address dynamic for a packaged web-view app?

The project is designed for local use, with the server built using JS and the client in HTML and JS. I want to package the client into a web-view app to make it easier to use. However, I'm currently hardcoding the server IP in the client’s JS. If I change the server machine, the IP will change as well, and I won’t be able to update it in the app once it's packaged. What can i do to dont need to change the ip even if i change the server machine?

19 Comments
2024/12/17
21:44 UTC

5

Do you pack your `CONTRIBUTING.md` file into your Node packages?

It's pretty standard to pack your README.md file into your package, but what about CONTRIBUTING.md? Is it just a waste of bytes to include, or is there value? Is there any value to your package consumers? Is there any value to third parties, like the NPM website?

5 Comments
2024/12/17
20:52 UTC

0

Drizzle ORM

I am using pgsql database for my Saas.
I use drizzle for my query but i didn't see the document of drizzle in detail about connection pool.
Dose drizzle handle release connection to pool auto after the query done (like client.release())?

if it is not, how to do that?

Thank you.

2 Comments
2024/12/17
19:37 UTC

Back To Top