orbitdb / field-manual

The Offical User's Guide to OrbitDB
210 stars 44 forks source link

Exception from require in Chapter 1 #33

Closed keepsimple1 closed 5 years ago

keepsimple1 commented 5 years ago

Hi, I am following the Chapter 1 (https://github.com/orbitdb/field-manual/blob/master/01_Tutorial/01_Basics.md) to learn the basics, and it seems that the following try block would throw exception when running in Node.js:

+ try {
+   const Ipfs = require('ipfs')
+   const OrbitDB = require('orbit-db')
+ } catch(e) {}

Is it expected? The exception I got is (I added console.log):

<myhome>/test-orbit-db/node_modules/proper-lockfile/lib/lockfile.js:61
                    return acquireLock(file, { ...options, stale: 0 }, callback);
                                               ^^^

SyntaxError: Unexpected token ...
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/hanxu/work/test-orbit-db/node_modules/proper-lockfile/index.js:3:18)

And later, it will fail to find "Ipfs" and fall into the code path for the browser. (window.NPP).

aphelionz commented 5 years ago

Hello! Thamks for writing. As of now this code will work with Node version 11 and above. What node version are you running? I.e. the output of node --version

keepsimple1 commented 5 years ago

Looks like my node is quite old then. It's version 8.1.2 . I will try to get it upgraded. Thanks!

aphelionz commented 5 years ago

A tool like nvm might make it easier: https://github.com/nvm-sh/nvm

keepsimple1 commented 5 years ago

Thanks. It turns out quite interesting:

aphelionz commented 5 years ago

Ah, yes! Sorry - the latest PR fixes that. You can use this in the meantime.

class NewPiecePlease {
  constructor (Ipfs, OrbitDB) {
    this.Ipfs = Ipfs
    this.OrbitDB = OrbitDB
  }
}

try {
    const Ipfs = require('ipfs')
    const OrbitDB = require('orbit-db')

    module.exports = exports = new NewPiecePlease(Ipfs, OrbitDB)
} catch (e) {
    window.NPP = new NewPiecePlease(window.Ipfs, window.OrbitDB)
}
aphelionz commented 5 years ago

The PR was merged so everybody should have that code update now :) Closing this but feel free to open more issues as you go through the rest of the tutorial!