2

Let's say I have javascript files on IPFS, for example, this. I want to build a piece of javascript (node) code that will retrieve the ipfs hash, and will then have to load the file(s) pointed to. So far I'm doing:

node.get(fileHash, (err, files) => {
    // some check for error
    files
    .filter(file => file.type === 'file')
    .forEach(file => {
        vm.runInThisContext(
            code    = file.content.toString('utf8'),
            options = { filename: file.name }
        );
    });
});

I don't really want to mess up with the filesystem (this will have to run in a browser) so I'd like to avoid writing the files and then requiring them.

Is there a better way to load javascript code that is stored in a variable (basically). I feel like I'm using some sort of eval ... which I don't like

1 Answer 1

3

You could load the modules from the IPFS HTTP Gateway

<script src="https://ipfs.io/ipfs/<cid>/mything.js" />

If the user has ipfs-companion installed, the resource will be fetched from the users local ipfs gateway at localhost:8080, and if not it will be fetched from the public gateway at ipfs.io. This could be interesting with es modules and import flavour

import foo from https://ipfs.io/ipfs/<cid>/index.js`

If you want to load the resources with js-ipfs as in your example, then you can use [ipfs.cat][2] to get the response instead of ipfs.get. You'll have to do some form of eval as you didnt ask the browser to fetch the script

// get the script
const data = await ipfs.cat('CidForYourScript')

// depending on how your script is packaged, eval it
const exports = (new Function(data.toString()))()

See this PR on js-ipfs for more discussion of this idea from the core developers: https://github.com/ipfs/js-ipfs/pull/1830

For more ideas on eval-ing js see: https://benclinkinbeard.com/posts/how-browserify-works/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.