node.jsnpmbittorrentwebtorrent

npm: cant import bencode module


I am trying to read torrent file data. To decode I want to use bencode package, but I cant import the bencode module. I tried google, youtube, stackoverflow. nope nothing found.

Code

// index.js

const fs = require('fs');
const bencode = require('bencode');

const torrent = bencode.decode(fs.readFileSync('../sintel.torrent'));
console.log(torrent.announce.toString("utf8"));

CMD

PS C:\Users\samad\Desktop\read-torrent\read-torrent-nodejs> node index     
node:internal/modules/cjs/loader:598
      throw e;
      ^

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in C:\Users\samad\Desktop\read-torrent\read-torrent-nodejs\node_modules\bencode\package.json
    at exportsNotFound (node:internal/modules/esm/resolve:294:10)
    at packageExportsResolve (node:internal/modules/esm/resolve:584:13)
    at resolveExports (node:internal/modules/cjs/loader:591:36)
    at Module._findPath (node:internal/modules/cjs/loader:668:31)
    at Module._resolveFilename (node:internal/modules/cjs/loader:1130:27)
    at Module._load (node:internal/modules/cjs/loader:985:27)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at Object.<anonymous> (C:\Users\samad\Desktop\read-torrent\read-torrent-nodejs\index.js:2:17)
    at Module._compile (node:internal/modules/cjs/loader:1376:14) {
  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
}

Node.js v20.10.0

Already Done

> npm update
> npm install bencode  # reinstalling
> npm cache clean --force
> npm audit fix --force

Note:

exports: is present in package.json file of bencode package.


Solution

  • The bencode package is an ES Module. You are using CommonJS. As the Node docs state:

    Using require to load an ES module is not supported because ES modules have asynchronous execution. Instead, use import() to load an ES module from a CommonJS module.

    I recommend you change your package.json to add the following:

    "type": "module",
    

    Then you can use ES Module import syntax like so:

    import * as fs from 'fs';
    import bencode from 'bencode'
    

    Note: once you change "type": "module" you will need to use import throughout your project in place of require().