20

What I would like to do is this curl operation in node.js.

curl -XPOST localhost:12060/repository/schema/fieldType -H 'Content-Type: application/json' -d '
{
  action: "create",
  fieldType: {
    name: "n$name",
    valueType: { primitive: "STRING" },
    scope: "versioned",
    namespaces: { "my.demo": "n" }
  }
}' -D -

Suggestions are appreciated.

Mxyk
  • 10,678
  • 16
  • 57
  • 76
XMen
  • 29,384
  • 41
  • 99
  • 151

3 Answers3

25

Although there are no specific NodeJS bindings for cURL, we can still issue cURL requests via the command line interface. NodeJS comes with the child_process module which easily allows us to start processes and read their output. Doing so is fairly straight forward. We just need to import the exec method from the child_process module and call it. The first parameter is the command we want to execute and the second is a callback function that accepts error, stdout, stderr.

var util = require('util');
var exec = require('child_process').exec;

var command = 'curl -sL -w "%{http_code} %{time_total}\\n" "http://query7.com" -o /dev/null'

child = exec(command, function(error, stdout, stderr){

console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);

if(error !== null)
{
    console.log('exec error: ' + error);
}

});

EDIT This is also a possible solution: https://github.com/dhruvbird/http-sync

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
mrryanjohnston
  • 353
  • 2
  • 7
  • Why use curl from the command line when you can use `http.request` or node.js directly – Raynos Sep 21 '11 at 12:26
  • 9
    It's just another option. He asked for curl, so I gave him curl :) – mrryanjohnston Sep 21 '11 at 12:33
  • 4
    CURL have way more options than http.request (including proxy support) – Ivan Castellanos Apr 13 '12 at 17:18
  • In some proxy configurations, it's maddening to try to get node to negotiate the proxy correctly when curl works without trouble. This is a decent workaround for those who have specific needs. – J E Carter II Jan 20 '17 at 20:59
  • See this answer as well, for attaching a listener to the child process if you want to process the returned results from curl. http://stackoverflow.com/questions/14332721/node-js-spawn-child-process-and-get-terminal-output-instantaneously – J E Carter II Jan 20 '17 at 21:10
13

Use request. request is the de-facto standard way to make HTTP requests from node.js. It's a thin abstraction on top of http.request

request({
  uri: "localhost:12060/repository/schema/fieldType",
  method: "POST",
  json: {
    action: "create",
    fieldType: {
      name: "n$name",
      valueType: { primitive: "STRING" },
      scope: "versioned",
      namespaces: { "my.demo": "n" }
    }
  }
});
Raynos
  • 166,823
  • 56
  • 351
  • 396
3

take a look at https://github.com/chriso/curlrequest

Last Rose Studios
  • 2,461
  • 20
  • 30