Меню

Node index js ошибка

Okay so I was trying to make a discord bot following a tutorial when I noticed some weird errors.

This is my code:

const Discord = require('discord.js');

const client = new Discord.Client();

const prefix = '-';

client.once('ready', () => {
    console.log('JokeBot is online!')
});

client.on('message', message => {
    if(!message.content.startsWith(prefix) || message.author.bot ) return;

    const args = message.content.slice(prefix.lenght).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'ping'){
        message.channel.send('pong!');
    }
});

client.login(YOUR_TOKEN);

And these are the errors:

Debugger attached.
Waiting for the debugger to disconnect...
internal/modules/cjs/loader.js:818
  throw err;
  ^

Error: Cannot find module 'node:events'
Require stack:
- /media/oli/MID/Projects/JS/Bot/node_modules/discord.js/src/client/BaseClient.js
- /media/oli/MID/Projects/JS/Bot/node_modules/discord.js/src/index.js
- /media/oli/MID/Projects/JS/Bot/index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
    at Function.Module._load (internal/modules/cjs/loader.js:667:27)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/media/oli/MID/Projects/JS/Bot/node_modules/discord.js/src/client/BaseClient.js:3:22)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/media/oli/MID/Projects/JS/Bot/node_modules/discord.js/src/client/BaseClient.js',
    '/media/oli/MID/Projects/JS/Bot/node_modules/discord.js/src/index.js',
    '/media/oli/MID/Projects/JS/Bot/index.js'
  ]
}
              

May I remind you that running npm install on those packages didn’t work and just returned a lot of npm errors.
I don’t know what to do
Edit:

It’s still saying that even when I updated node.js

Hi Jason.

I tried downgrading node to 8.9.4 but I’m still getting the same problem. Any ideas? I’m included a screenshot of nvm

________________________________
From: Jason Etcovitch <notifications@github.com>
Sent: 01 March 2018 16:16:10
To: JasonEtco/flintcms
Cc: Maria Dada; Mention
Subject: Re: [JasonEtco/flintcms] node index.js in my command line returns nothing (#68)

Hey @mariadada<https://github.com/mariadada>! Sorry you’re having problems

😭

I haven’t done extensive testing, but I’ve noticed that many of the integration tests fail in Node 9.x, so I’m thinking that’s probably the culprit. Really glad you included version numbers, super helpful!

You can try downgrading to Node 8.9.4 (using nvm<https://github.com/creationix/nvm> is the way to go). Let me know if that works for you — I’d love to support 9.x, but I’m a little strapped for time to work on that

😁


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<#68 (comment)>, or mute the thread<https://github.com/notifications/unsubscribe-auth/AjF2a52S94yqr-pPSGemqjxLq0QVYophks5taB7FgaJpZM4SYjiX>.

This email and any attachments are intended solely for the addressee and may contain confidential information. If you are not the intended recipient of this email and/or its attachments you must not take any action based upon them and you must not copy or show them to anyone. Please send the email back to us and immediately and permanently delete it and its attachments. Where this email is unrelated to the business of University of the Arts London or of any of its group companies the opinions expressed in it are the opinions of the sender and do not necessarily constitute those of University of the Arts London (or the relevant group company). Where the sender’s signature indicates that the email is sent on behalf of UAL Short Courses Limited the following also applies: UAL Short Courses Limited is a company registered in England and Wales under company number 02361261. Registered Office: University of the Arts London, 272 High Holborn, London WC1V 7EY

Cover image for How i fixed the circular dependency issue in my Node.js application

Alisson Zampietro

I’m going introduce you in a problem that maybe you’ve been through and some point in your node.js career.
Usually i split my business logic from anything else in my code (let’s name it as a service), been my business layer responsible to trigger the resources that are required to make some action. Sometimes, one item in this business layer needs to use another one in the same layer.


Example:

CustomerService requires UserService to create the login credentialsCustomerService requires UserService to create the login credentials

Both services depending each other and in another moment, UserService will call CustomerService to validate Customer profile.


Failure scenario:

File structure

|—/services/CustomerService.js

const UserService = require('./UserService')

class CustomerService{
    create() {
        UserService.create();
        console.log('Create Customer');
    }

    get() {
       return {
          name: 'test'
       }
    }
}

module.exports = new CustomerService;

Enter fullscreen mode

Exit fullscreen mode

|—/services/UserService.js

const CustomerService = require('./CustomerService')
class UserService {
    create() {
        console.log('Create user');
    }

    get() {
        let customer = CustomerService.get();
        console.log({customer});
    }
}
module.exports = new UserService;

Enter fullscreen mode

Exit fullscreen mode

|—/index.js

const CustomerService = require('./services/CustomerService');
const UserService = require('./services/UserService');

CustomerService.create();
UserService.get();

Enter fullscreen mode

Exit fullscreen mode

So, after implementing this code and run node index.js in your terminal, you gonna get the following error:

Error due circular dependency

You may be thinking: WTF??? But this method does exist!!!!

Yes, that was my reaction. You’re getting this error due the circular dependency, which happens when you create a dependecy between two modules, it means that we’re importing and using UserService inside CustomerService and vice-versa.

How can we solve this? One possible solution.

We’re going to load our modules in a centralized file called index.js, so after this, we’re going to import only the index.js file and specify the Objects that we need to use.

Centralized module

Hands on:

1 — Create a index.js file inside the services folder (Attention: it’s our crucial code snippet):

|—/services/index.js

const fs = require('fs');
const path = require('path');
const basename = path.basename(__filename);
const services = {};

// here we're going to read all files inside _services_ folder. 
fs
    .readdirSync(__dirname)
    .filter(file => {
        return (file.indexOf('.') !== 0) &&
                (file !== basename) &&
                (file.slice(-3) === '.js') &&
                (file.slice(-8) !== '.test.js') &&
                (file !== 'Service.js')
    }).map(file => {
        // we're are going to iterate over the files name array that we got, import them and build an object with it
        const service = require(path.join(__dirname,file));
        services[service.constructor.name] = service;
    })

    // this functionality inject all modules inside each service, this way, if you want to call some other service, you just call it through the _this.service.ServiceClassName_.
    Object.keys(services).forEach(serviceName => {
        if(services[serviceName].associate) {
            services[serviceName].associate(services);
        }
    })

module.exports = services;

Enter fullscreen mode

Exit fullscreen mode

2 — Let’s create a Parent class that gonna be inherited by each service that we create.

|—/services/Service.js

class Service {
    associate(services) {
        this.services = services;
    }
}

module.exports = Service;

Enter fullscreen mode

Exit fullscreen mode

3 — Let’s rewrite ou code to check how it’s gonna be.

|—/services/CustomerService.js

const Service = require('./Service')
class CustomerService extends Service{
    create() {
        this.services.UserService.create();
        console.log('Create Customer');
    }
    get() {
       return {
          name: 'test'
       }
    }
}

module.exports = new CustomerService;

Enter fullscreen mode

Exit fullscreen mode

|—/services/UserService.js

// now you only import the Service.js
const Service = require('./Service.js')
class UserService extends Service{
    create() {
        console.log('Create user');
    }

    get() {
        // now we call the service the we want this way
        let customer = this.services.CustomerService.get();
        console.log({customer});
    }
}
module.exports = new UserService;

Enter fullscreen mode

Exit fullscreen mode

4 — now., let’s see how we’re going to call the services outside the services folder.

// now we only import the index.js (when you don't set the name of the file that you're intending to import, automatically it imports index.js)
const {CustomerService, UserService} = require('./services/')
// and we call this normally
CustomerService.create();
UserService.get();

Enter fullscreen mode

Exit fullscreen mode


PROS:

  • Now it’s easier to load another service, without getting any circular dependecy error.
  • if you need to use a service inside other service, you just have to call the property this.service.NameOfTheService.

CONS:

  • It’s not trackeable anymore by your IDE or Code Editor, as the import handler is inside our code and it’s not straight in the module that you want to use anymore.
  • A small loss of performance due the loading of all modules, although some of them are not used.

If you think that there’s something confusing, or impacting the understanding, or that i can improve, please i’m going to appreciate your feedback.

See you guys and thanks a lot

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Nod32 ошибка открытия сокета
  • Nod32 ошибка активации аст 0