Home > Net >  How to install nanoid in nodejs?
How to install nanoid in nodejs?

Time:01-27

I am currently trying to import and use nanoid in my (Firebase) nodejs project. I installed it with

npm i nanoid

and I tried to import it with

import { nanoid } from 'nanoid'

and

import { nanoid } from '../node_modules/nanoid/nanoid.js'

Everything I tried failed. I am a complete beginner with nodejs and js itself, but no Website or Documentation helped me fixing the problem. I just want an unique id :(

heres my index.html (reduced to minimum:

<!DOCTYPE html>
<html>
  <head>
    <title>Welcome to Firebase Hosting</title>

    !!!Here are Firebase imports!!!
 
    <script defer src="/__/firebase/init.js?useEmulator=true"></script>
    <link rel="stylesheet" href="style.css">


  </head>
  <body>

    <div >

    <div >
    <h1 id="title">Sign up</h1>
    <iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>
    <form id="form" onsubmit="return false">
    


      <!-- Birth date Input (required) -->
      <div >
          <input id="date" onfocus="(this.type = 'date')"  type="text" name="birthdate" placeholder="Geburtsdatum" required />
      </div>

      <!-- Checkbox 1 -->
      <div >
          <input type="checkbox" id="cb1" >
          <label for="cb1">I agree with terms and conditions</label>
      </div>


      <input  id="registerUser" type="submit" value="Anmelden"/>

    </form>
  </div>
    </div>

    <script src="app.js"></script>

  </body>
</html>

app.js:

const nanoid = require('nanoid');

document.addEventListener('DOMContentLoaded', event => {
    const app = firebase.app();
    const db = firebase.firestore();

    const users = db.collection('users');
})


async function addUser() {
    console.log('adding User');
    const db = firebase.firestore();
    const users = db.collection('users');   
    const data = {
        email: document.getElementById("email").value,
        test_active: false
    };

    
    code = nanoid(10).toString();
    await users.doc(code).set(data);  
}

CodePudding user response:

I am using this nanoid, lemme share my POC,

import {nanoid} from 'nanoid';
const id = nanoid(length).toString();

CodePudding user response:

i am using nanoid version 2.1.9

const nanoid = require('nanoid')
let id = nanoid(5)

CodePudding user response:

Try adding rounded brackets around as such { nanoid } before requiring it and then declaring a var named ID to store it :

var { nanoid } = require('nanoid');

var ID = nanoid();

  •  Tags:  
  • Related