6

The dApp I'm building requires a traditonal backend and as a result I need to use Node.js and MongoDB alongside Truffle. Does anybody know how to set Node to work with Truffle? Thanks!

14

When you run truffle migrate, Truffle compiles the contract to a JSON file located into build/contracts/MyContract.json

This JSON file can be used by a Node library called truffle-contract like that:

// Import libraries
var Web3            = require('web3'),
    contract        = require("truffle-contract"),
    path            = require('path')
    MyContractJSON  = require(path.join(__dirname, 'build/contracts/MyContract.json'));

// Setup RPC connection   
var provider    = new Web3.providers.HttpProvider("http://localhost:8545");


// Read JSON and attach RPC connection (Provider)
var MyContract = contract(MyContractJSON);
MyContract.setProvider(provider);

// Use Truffle as usual
MyContract.deployed().then(function(instance) {
    return instance.myFunction.call(arg1, arg2, {from: '0x************************'})

}).then(function(result) {
    console.log(result);

}, function(error) {
    console.log(error);
}); 

I published a working example with Metacoin here. To run it:

  1. npm install
  2. truffle migrate (testrpc or geth must run)
  3. node index.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.