Unable to get response using node curl package on Nodejs - node.js

I'm using node curl to make a call to a WS. I wrote a simple function that just issues a request and I'm logging the response. This is how my server.js looks:
var http = require('http');
var curl = require('node-curl');
var config = require('./config');
var cfgObj = new config.config();
function start(port) {
function onRequest(request, response) {
console.log("Request received");
var options = {
VERBOSE: 1,
RAW: 1
};
curl.debug = 1;
curl.setDefaultOptions(options);
curl('www.google.com', function(err) {
console.log(this.body);
});
}
http.createServer(onRequest).listen(port);
}
cfgObj.getConfig(null, function(data) {
start(data.port);
});
cfgObj just contains the port number. It connected to the host properly and I even got HTTP 200 OK response:
[cURL 1] receive 2242 bytes
[cURL 1] receive succeeded.
But in the end, it says:
Bus error: 10
What does this mean?
The control never calls the function where I'm printing this.body. I even tried using http request but that gives me "socket hang up" error.
I have been unable to debug this issue. Any clues?

node-curl is broken, when I try to use it on my Mac I get the same error:
[2] 34539 bus error node test.js
(a bus error is an error which occurs when a program tries to write to an invalid memory location)
Here's a replacement for node-curl: https://github.com/mikeal/request

Related

Slack node js program running session shut down

Sorry to disturb. I am programming a Slack robot to reply user message by using the API
In the morning, it works totally okay. Then after I returned back from my office it just shut down and show me this error
Jiatongs-MacBook-Pro:news-bot jiatongli$ node index.js
Assertion failed: token must be defined
/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:105
throw e;
^
Error: not_authed
at _api.then.fail (/Users/jiatongli/Desktop/news-bot/node_modules/slackbots/index.js:46:33)
at Array.<anonymous> (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:773:56)
at callFns (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:24:35)
at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
at _api.then.fail (/Users/jiatongli/Desktop/news-bot/node_modules/slackbots/index.js:46:19)
at Array.<anonymous> (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:773:56)
at callFns (/Users/jiatongli/Desktop/news-bot/node_modules/vow/lib/vow.js:24:35)
at process._tickCallback (internal/process/next_tick.js:61:11)
Jiatongs-MacBook-Pro:news-bot jiatongli$
I personally have no idea what is going on because it seems like the program itself do not have bug. What i miss?
Here is the code in my index.js file:
var SlackBot = require("slackbots");
var request = require("request");
var NewsAPI = require("newsapi");
var unirest = require("unirest");
var API_KEY = process.env.API_KEY;
var Slack_API = process.env.Slack_API;
// create a bot
var bot = new SlackBot({
token: Slack_API,
name: "aloha-ai"
});
bot.on("message", msg => {
switch (msg.type) {
case "message":
// we only want to listen to direct messages that come from the user
if (msg.channel[0] === "D" && msg.bot_id === undefined) {
getRandomTechNews(postMessage, msg.user)
}
break
}
})
const postMessage = (message, user) => {
bot.postMessage(user, message, {
as_user: true
});
}
const getRandomTechNews = (callback, user) => {
unirest.get("https://nuzzel-news-v1.p.rapidapi.com/news?count=10&q=product")
.header("X-RapidAPI-Host", "nuzzel-news-v1.p.rapidapi.com")
.header("X-RapidAPI-Key", API_KEY)
.end(function (response) {
var newsJSON = response.body;
var news = "*Viral News* in product : \n\n\n\n";
for (i = 0; i < newsJSON.results.stories.length; i++) {
news += "_Excerpt:_ \n" + ">" + newsJSON.results.stories[i].excerpt + "\n"
news += "_Let's see the article!_ \n" + newsJSON.results.stories[i].url + "\n\n\n"
};
callback(news, user);
});
}
Your error message seems to indicate that your program is not authenticated with the Slack API: Error: not_authed
Since you are retrieving your API key and token from environment variables:
var API_KEY = process.env.API_KEY;
var Slack_API = process.env.Slack_API;
my guess is that you have started a new terminal session where you have not yet set that environment variable, or you are on a different computer where it is not set.
Before running your program, try exporting those variables from the command line:
export API_KEY=<my-api-key>
export Slack_API=<my-token>
If you have security concerns about your API keys showing up in your bash history you can do one of two things (these are examples of things that I do, but there are probably better, safer practices out there):
You can put an empty space before your command [space]export API_KEY=<my-api-key> instead of export API_KEY=<my-api-key>. This will make it so the command does not show up in your history.
You can put your export commands in a separate file called e.g., ~/.secrets and then run the command source ~/.secrets which will run your export commands.
Probably these will give you a sense of security rather than actual security though, since you can just echo the value of the environment variables, but I personally like taking one of these steps as an extra precaution.
i use this answer and can solve it.
Add a bot https://my.slack.com/services/new/bot and put the token
do you get token for your bot from above url:
did you set this ?

Module `fs` does not exist in the Haste module map

I'm new to Node.js and react-native. I followed the sample on send_telemetry.js exactly but when I run my react-native app I get an error: "The development server returned response error code 500.
the error message is:
bundling failed: Error: Unable to resolve module fs from ProjectPath\node_modules\azure-iot-device\lib\module_client.js: Module fs does not exist in the Haste module map";
Im running:
Node.js v10.15.3
NPM 6.4.1
react-native#0.59.2
First error was the same with Unable to resolve module events,
I can install events,
but the fs module is: "This package name is not currently in use, but was formerly occupied by another package. To avoid malicious use, npm is hanging on to the package name, but loosely, and we'll probably give it to you if you want it."
var Protocol = require('azure-iot-device-http').Http;
var DeviceClient = require('azure-iot-device').Client;
var Message = require('azure-iot-device').Message;
var connectionString = 'my connection string';
var client = DeviceClient.fromConnectionString(connectionString, Protocol);
function ConnectionTest(err) {
if (err) {
console.log('Could not connect: ' + err);
} else {
console.log('Client connected');
}
client.close(function () {
process.exit(0);
});
};
export async function Test() {
client.open(ConnectionTest);
};
Basically I need to know how to get the azure IOT hub client working in my react-native app (not using Expo).
Im pretty much stumped so any help would greatly be appreciated.
A dependency module is missing ... which is fs ...
this file-system npm module is incompatible with react-native ... cause it has it own different environment.
I had "import { symlink } from 'fs';" randomly pop up in one of my scripts. Once I deleted this line same issue you had went away. I would search your whole project for that line.

module is not defined error

I am using nodejs in my meteor app and I added packages using mrt add npm and then in my client directory in packages.json I added skimlinksjs and its version and it is added to my app.
When I tried to using them in my app in server side code like this,
var res;
var skim = Meteor.require('skimlinksjs');
var apili = Meteor.require('/config.js');
skim.setup(apili.key);
skim.query({
searchFor: "title:\"moto g\"",
fq: "country:US"
}, function(err,data) {
res=data.skimlinksProductAPI.numFound;
}
);
return res;
and my config.js file is like this
module.exports = {
key: "xxxxxxx"
}
whenI'm running this application it is showing error like
module not defined
What went wrong with my code or is there any need to install other packages?
I just got the answer
Write this function in server side code
function returnAllResult()
{
var skimlinks = Meteor.require('skimlinksjs');
skimlinks.setup("xxx");
var skimlinks_query = Async.wrap(skimlinks.query);
var result = skimlinks_query({
searchFor: "title:\"moto g\"",
fq: "country:US",
rows:5
});
return result;
}
to know about asynchronous functions watch this
and then in my server side methods call this
apiresult:function()
{
var response = returnAllResult();
return response.skimlinksProductAPI.products[0].merchant;
}
that's it working fine now. Hope this helps someone

Dynamic arguments for ZINTERSTORE with node_redis

I'm trying to use the ZINTERSTORE command of redis from node.js using node_redis:
//node.js server code
var redis = require("redis");
var client = redis.createClient();
// ... omitted code ...
exports.searchImages = function(tags, page, callback){
//tags = ["red", "round"]
client.ZINTERSTORE("tmp", tags.length, tags.join(' '), function(err, replies){
//do something
});
}
But the call client.ZINTERSTORE throws the error: [Error: ERR syntax error]. Passing in tags as an array (instead of using tags.join(' ')) throws the same error.
Where can I find the correct syntax for this command? The source code for node_redis has it buried in the javascript parser, but it's tricky to see what's going on without 'stepping through' the code. Is there a good way to do step through debugging with node.js?
There are multiple ways to debug a Redis client with node.js.
First you can rely on the Redis monitor feature to log every commands received by the Redis server:
> src/redis-cli monitor
OK
1371134499.182304 [0 172.16.222.72:51510] "info"
1371134499.185190 [0 172.16.222.72:51510] "zinterstore" "tmp" "2" "red,round"
You can see the zinterstore command received by Redis is ill-formed.
Then, you can activate the debugging mode of node_redis by adding the following line in your script:
redis.debug_mode = true;
It will output the Redis protocol at runtime:
Sending offline command: zinterstore
send ncegcolnx243:6379 id 1: *4
$11
zinterstore
$3
tmp
$1
2
$9
red,round
send_command buffered_writes: 0 should_buffer: false
net read ncegcolnx243:6379 id 1: -ERR syntax error
Then, you can use node.js debugger. Put a debugger breakpoint in the code in the following way:
function search(tags, page, callback) {
debugger; // breakpoint is here
client.ZINTERSTORE("tmp", tags.length, tags, function(err, replies){
console.log(err);
console.log(replies);
callback('ok')
});
}
You can then launch the script with node in debug mode:
$ node debug test.js
< debugger listening on port 5858
connecting... ok
break in D:\Data\NodeTest\test.js:1
1 var redis = require("redis");
2 var client = redis.createClient( 6379, "ncegcolnx243" );
3
debug> help
Commands: run (r), cont (c), next (n), step (s), out (o), backtrace (bt), setBreakpoint (sb), clearBreakpoint (cb),
watch, unwatch, watchers, repl, restart, kill, list, scripts, breakOnException, breakpoints, version
debug> cont
break in D:\Data\NodeTest\test.js:8
6 function search(tags, page, callback) {
7
8 debugger;
9 client.ZINTERSTORE("tmp", tags.length, tags, function(err, replies){
10 console.log(err);
... use n(ext) and s(tep) commands ...
By stepping through the code, you will realize that the command array is not correct because the tags are serialized and processed as a unique parameter.
Changing the code as follows will fix the problem:
var cmd = [ "tmp", tags.length ];
client.zinterstore( cmd.concat(tags), function(err, replies) {
...
});

Making an HTTP request using node.js throws EAFNOSUPPORT

I'm trying to make a simple HTTP GET request using node.js, but I'm running into trouble using node.js v0.3.4-pre (i.e. compiled from HEAD as of this morning). Here's my code:
var cli = require('cli');
var http = require('http');
var url = require('url');
cli.parse();
cli.main(function(args, opts) {
this.debug(args[0]);
var siteUrl = url.parse(args[0]);
var site = http.createClient(siteUrl.port, siteUrl.host);
console.log(siteUrl);
var request = site.request("GET", siteUrl.pathname, {'host' : siteUrl.host})
request.end();
request.on('response', function(response) {
response.setEncoding('utf8');
console.log('STATUS: ' + response.statusCode);
response.on('data', function(chunk) {
console.log("DATA: " + chunk);
});
});
});
Here's the error that I get:
node.js:68
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: EAFNOSUPPORT, Address family not supported by protocol family
at doConnect (net.js:499:19)
at Client.connect (net.js:652:30)
at Client._ensureConnection (http.js:1033:10)
at Client.request (http.js:1048:8)
at Object.<anonymous> (/Users/paul/Desktop/readify.js:16:21)
at /usr/local/lib/node/.npm/cli/0.2.3-2/package/cli.js:995:18
at Object.main (/usr/local/lib/node/.npm/cli/0.2.3-2/package/cli.js:1000:9)
at Object.<anonymous> (/Users/paul/Desktop/readify.js:10:5)
at Module._compile (node.js:359:32)
at Object..js (node.js:367:14)
Found the bug, siteUrl.port will be undefined unless the URL explicitly names a port. So, the solution is:
var site = http.createClient(siteUrl.port || 80, siteUrl.host);
var site = http.createClient(siteUrl.port, siteUrl.host);
should rather be
var site = http.createClient(siteUrl.port || 80, siteUrl.hostname);
The same error message appeared on my very old XPSP2-box for ANY connect()-attempts. E.g npm wasn't able to do anything, and simple http requests failed.
While trying to find a solution, this post appeared all over the place, but its not the same issue.
In my case it had to do with WSAIoctl(...) always returning WSAEOPNOTSUPP when querying for WSAID_CONNECTEX, which seemed strange. This led me to a post recommending doing a "netsh winsock reset" from the cmd, which fixed the problem!

Resources