Installed Node.js and socketio io (using npm). Node Hello World works.
Created app.js with the following line:
var io = require('socket.io')();
node node app.js throws exception:
io_test.js:1
ts, require, module, __filename, __dirname) { var io = require('socket.io')();
^
TypeError: object is not a function
How to fix?
OSX 10.7.5. Node.js 0.8.18.
Replace that line with
var io = require('socket.io').listen(8080);
Basically, if you read the error description, the require('socket.io') is returning an object, not a function that you can call. If you look at the example code on the socket.io website, you can see that you can call listen() on the object returned. So, you could also write it like this:
var sockio = require('socket.io')
var io = sockio.listen(8080)
Related
I am using truffle with mocha to test my smart contract. I have required web3 like so
const web3 = require('web3')
the import seems only to work partially.
for example, this statement works just fine
const amount = web3.utils.toWei('0.23')
however this statement
const balance = await web3.eth.getBalance(myContract.address)
causes the following error message:
TypeError Cannot read property 'getBalance' of undefined.
Moreover, Visual Studio Code gives me the following error message if I hover of the word eth in this following code:
web.eth.getBalance(myContract.address)
Property 'eth' does not exist on typeof import (/Users/eitanbronschtein/Desktop/fundraiser/node_modules/web3/types/index)
I am using javascript and not typescript.
What is going on?
web3 does not work without provider. install ganach-cli
const ganache = require("ganache-cli");
const Web3 = require("web3");
// this is in local ganache network gasLimit has to be set to 10million and and factory gas must be 10million
// if u get error about gasLimit, this keep changing. look for docs
const web3 = new Web3(ganache.provider({ gasLimit: 10000000 }));
If you set truffle suit, you should have "test" directory in your project and web3 would be already set and available globally
From https://web3js.readthedocs.io/en/v1.7.5/web3.html:
The Web3 class is an umbrella package to house all Ethereum related modules.
var Web3 = require('web3');
// "Web3.providers.givenProvider" will be set if in an Ethereum supported browser.
var web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546');
//now you can do web3.eth
Currently working with the latest releases of the hyperledger development environment and am working through the admin services. The example code for admin -> deploy is documented as:
// Deploy a Business Network Definition
var adminConnection = new AdminConnection();
var businessNetworkDefinition = BusinessNetworkDefinition.fromArchive(myArchive);
return adminConnection.deploy(businessNetworkDefinition)
.then(function(){
// Business network definition deployed
})
.catch(function(error){
// Add optional error handling here.
});
In the code as provided, the second line fails as BusinessNetworkDefinition is not a part of the composer-admin node module. I have two options for creating a BusinessNetworkDefinition, one is to use composer-client. This fails with the following message: TypeError: composerClient.BusinessNetworkDefinition is not a constructor
The code used for this attempt is summarized here:
'use strict';
var fs = require('fs');
var path = require('path');
var composer = require('composer-admin');
var composerClient = require('composer-client');
var composerCommon = require('composer-common');
var businessNetworkDefinition = new composerClient.BusinessNetworkDefinition();
The other option is to use composer-common, which fails with the following message: TypeError: businessNetworkDefinition.fromArchive is not a function
The code used for this attempt is:
var fs = require('fs');
var path = require('path');
var composer = require('composer-admin');
var composerClient = require('composer-client');
var composerCommon = require('composer-common');
var net_identifier = "zerotoblockchain-network#0.1.6";
var net_description = "Z2B network";
var net_package = require("../../../../network/package.json");
var net_readme = "../../../../README.md";
var businessNetworkDefinition = new composerCommon.BusinessNetworkDefinition(net_identifier, net_description, net_package, net_readme);
var archive = businessNetworkDefinition.fromArchive(req.body.myArchive);
where req.body.myArchive is the name of the archive file to be used in the fromArchive method. Inspecting the BusinessNetworkDefinition created via the new command shows the following:
object property: modelManager
object property: aclManager
object property: queryManager
object property: scriptManager
object property: introspector
object property: factory
object property: serializer
object property: metadata
So, two questions:
One: What was created with the new command and
Two: How do I correctly create a BusinessNetworkDefinition object which as a fromArchive() function in it?
The example code in the hyperledger composer documentation is flawed. Following is code which will successfully execute a business network deploy.
(1) Required definitions:
let fs = require('fs');
let path = require('path');
let composerAdmin = require('composer-admin');
const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefinition;
The following is written as an exportable, routable routine in nodejs and has been tested through from client (browser). Client passes in name of network to deploy. File layout is:
root/network/dist/network-archive-file.bna
(2) Read in the archive file and create an admin connection:
/**
* Deploys a new BusinessNetworkDefinition to the Hyperledger Fabric. The connection must be connected for this method to succeed.
* #param {express.req} req - the inbound request object from the client
* req.body.myArchive: _string - string name of object
* req.body.deployOptions: _object - string name of object
* #param {express.res} res - the outbound response object for communicating back to client
* #param {express.next} next - an express service to enable post processing prior to responding to the client
* returns composerAdmin.connection - either an error or a connection object
* #function
*/
exports.deploy = function(req, res, next) {
let newFile = path.join(path.dirname(require.main.filename),'network/dist',req.body.myArchive);
let archiveFile = fs.readFileSync(newFile);
let adminConnection = new composerAdmin.AdminConnection();
(3) Invoke the (asynchronous) fromArchive function and then deploy the result of the fromArchive invocation.
return BusinessNetworkDefinition.fromArchive(archiveFile)
.then(function(archive) {
adminConnection.connect(config.composer.connectionProfile, config.composer.adminID, config.composer.adminPW)
.then(function(){
adminConnection.deploy(archive)
(4). Respond to the (browser based) request:
.then(function(){
console.log('business network deploy successful: ');
res.send({deploy: 'succeeded'});
})
.catch(function(error){
console.log('business network deploy failed: ',error);
res.send({deploy: error});
});
... (5) and for anyone copying all the code, a few closing braces:
});
});
};
Using the JavaScript SDK, what kind of object would be returned on the following query:
var groupQuery = new Parse.Query('some_valid_class');
var group = groupQuery.get('some_valid_object_id');
console.log(group);
I only see [object Object] in the log.
thanks!
On Cloud Code - You can't print objects directly as we usually does in console of browser.
You have to use console.log(JSON.stringify(yourObject))
Although the documentation doesn't say so, I believe the get method returns a Promise. Here is an example for getting the actual object taken from the documentation:
var query = new Parse.Query(MyClass);
query.get(myId, {
success: function(object) {
// object is an instance of Parse.Object.
},
error: function(object, error) {
// error is an instance of Parse.Error.
}
});
In the success-function a Parse.Object is provided.
You can find all the info at the Parse JavaScript SDK & Cloud Code Reference
Specific Parse.Query.get() documentation here: https://parse.com/docs/js/symbols/Parse.Query.html#get
The following exception:
SocketIOException: Unexpected handshake error in client (OS Error: errno = -12268)
#0 _SecureFilterImpl.handshake (dart:io-patch:849:8)
#1 _SecureSocket._secureHandshake (dart:io:7382:28)
#2 _SecureSocket._secureConnectHandler._secureConnectHandler (dart:io:7294:21)
#3 _Socket._updateOutHandler.firstWriteHandler (dart:io-patch:773:64)
#4 _SocketBase._multiplex (dart:io-patch:408:26)
#5 _SocketBase._sendToEventHandler.<anonymous closure> (dart:io-patch:509:20)
#6 _ReceivePortImpl._handleMessage (dart:isolate-patch:37:92)
results from the following code:
String url = "https://www.google.com";
HttpClient client = new HttpClient();
HttpClientConnection conn = client.getUrl(new Uri(url));
conn.onResponse = (HttpClientResponse resp) {
print ('content length ${resp.contentLength}');
print ('status code ${resp.statusCode}');
InputStream input = resp.inputStream;
input.onData = () {
print(codepointsToString(input.read()));
};
input.onClosed = () {
print('closed!');
client.shutdown();
};
};
Note that if I replace the url with "http" instead of "https", it works as expected.
Bug report is here.
Update: See the answer of William Hesse for Dart version >= 1.12.
I have the same error with Dart SDK version 0.2.9.9_r16323. In the issue 7541 :
The SecureSocket library needs to be initialized explicitly before using secure networking. We are working on making it initialize automatically the first time you use it, but that is not committed yet. To use just the default root certificates (well known certificate authorities), call SecureSocket.initialize()
in your main() routine, before you do any networking.
Thus, by adding SecureSocket.initialize() before your code, it works as expected.
After r16384 this explicit initialization is optional.
SecureSocket.initialize() is now optional. If you don't call it, it is the same as if you had called it with no parameters. If you call it explicitly, you must do so once, and before creating any secure connections. You need to call it explicitly if you are making server sockets, since they need a certificate database and a password for the key database.
The secure networking library has changed since this question was written. There is no SecureSocket.initialize() function anymore, and many other methods and objects have changed names. The working equivalent code for Dart 1.12 and later is:
import "dart:io";
main() async {
Uri url = Uri.parse("https://www.google.com");`
var client = new HttpClient();
var request = await client.getUrl(url);
var response = await request.close();
var responseBytes = (await response.toList()).expand((x) => x);
print(new String.fromCharCodes(responseBytes));
client.close();
}
So I'm building a multipart form uploader over ajax on node.js, and sending progress events back to the client over socket.io to show the status of their upload. Everything works just fine until I have multiple clients trying to upload at the same time. Originally what would happen is while one upload is going, when a second one starts up it begins receiving progress events from both of the forms being parsed. The original form does not get affected and it only receives progress updates for itself. I tried creating a new formidable form object and storing it in an array along with the socket's session id to try to fix this, but now the first form stops receiving events while the second form gets processed. Here is my server code:
var http = require('http'),
formidable = require('formidable'),
fs = require('fs'),
io = require('socket.io'),
mime = require('mime'),
forms = {};
var server = http.createServer(function (req, res) {
if (req.url.split("?")[0] == "/upload") {
console.log("hit upload");
if (req.method.toLowerCase() === 'post') {
socket_id = req.url.split("sid=")[1];
forms[socket_id] = new formidable.IncomingForm();
form = forms[socket_id];
form.addListener('progress', function (bytesReceived, bytesExpected) {
progress = (bytesReceived / bytesExpected * 100).toFixed(0);
socket.sockets.socket(socket_id).send(progress);
});
form.parse(req, function (err, fields, files) {
file_name = escape(files.upload.name);
fs.writeFile(file_name, files.upload, 'utf8', function (err) {
if (err) throw err;
console.log(file_name);
})
});
}
}
});
var socket = io.listen(server);
server.listen(8000);
If anyone could be any help on this I would greatly appreciate it. I've been banging my head against my desk for a few days trying to figure this one out, and would really just like to get this solved so that I can move on. Thank you so much in advance!
Can you try putting console.log(socket_id);
after form = forms[socket_id]; and
after progress = (bytesReceived / bytesExpected * 100).toFixed(0);, please?
I get the feeling that you might have to wrap that socket_id in a closure, like this:
form.addListener(
'progress',
(function(socket_id) {
return function (bytesReceived, bytesExpected) {
progress = (bytesReceived / bytesExpected * 100).toFixed(0);
socket.sockets.socket(socket_id).send(progress);
};
})(socket_id)
);
The problem is that you aren't declaring socket_id and form with var, so they're actually global.socket_id and global.form rather than local variables of your request handler. Consequently, separate requests step over each other since the callbacks are referring to the globals rather than being proper closures.
rdrey's solution works because it bypasses that problem (though only for socket_id; if you were to change the code in such a way that one of the callbacks referenced form you'd get in trouble). Normally you only need to use his technique if the variable in question is something that changes in the course of executing the outer function (e.g. if you're creating closures within a loop).