Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a json file from a url using node js (express)

I'm a node.js beginner. I'm trying to request a json file from a url (i.e 'http://www.example.com/sample_data.json'). My goal is to download/request the file only once when the server loads and then save it on the client side so I can manipulate/change it locally. I tried

var file = request('http//exmaple.com/sample_data.json')

but it returns an import module error. If anyone could give me a start that would be great! thanks

like image 724
Alon Weissfeld Avatar asked Apr 24 '15 17:04

Alon Weissfeld


2 Answers

To do that i would use the request module.

var request = require('request');
request('http//exmaple.com/sample_data.json', function (error, response, body) {
  if (!error && response.statusCode == 200) {
     var importedJSON = JSON.parse(body);
     console.log(importedJSON);
  }
})

For more information about the module check this link: https://github.com/request/request

like image 115
Kauê Gimenes Avatar answered Nov 15 '22 22:11

Kauê Gimenes


Just some basics about node, and some first things to try:

1) request is a good choice to use for getting the file, but did you do an npm install? "npm install request --save"

2) in order to use the module, you have to "require" it at the top of your code, like: var request = require('request');

I'd start by checking those things first.

like image 44
Clayton Gulick Avatar answered Nov 15 '22 22:11

Clayton Gulick