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!
1 Answer
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:
npm install
truffle migrate
(testrpc or geth must run)node index.js
-
So you could insert
truffle develop
before step 2, right? Oh no that won't work as it will put you in to a truffle console. Ok so in separate terminalganache-cli -p 8545
– HankCaSep 20 at 1:05