Node.js modules you should know about: request
Hey everyone! This is the fourth post in my new node.js modules you should know about article series.
The first post was about dnode - the freestyle rpc library for node, the second was about optimist - the lightweight options parser for node, the third was about lazy - lazy lists for node.
This time I'll introduce you to a very awesome module called request by Mikeal Rogers. Request is the swiss army knife of HTTP streaming.
Check this out:
var fs = require('fs') var request = require('request'); request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
Pow! You just streamed the response of HTTP request to http://google.com/doodle.png
into doodle.png
local file!
Here is more awesome stuff:
var fs = require('fs') var request = require('request'); fs.readStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
Pow! It streamed your local file file.json
to http://mysite.com/obj.json
as HTTP PUT request!
var request = require('request'); request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
Pow! This just streamed a HTTP GET from http://google.com/img.png
to HTTP PUT to http://mysite.com/img.png
.
At Browserling we use this module for streaming data to and from couchdb. Here is an example that saves a JSON document at mikeal's test couchdb:
var request = require('request') var rand = Math.floor(Math.random()*100000000).toString() request({ method: 'PUT', uri: 'http://mikeal.iriscouch.com/testjs/' + rand, multipart: [ { 'content-type': 'application/json', 'body': JSON.stringify({ foo: 'bar', _attachments: { 'message.txt': { follows: true, length: 18, 'content_type': 'text/plain' } } }) }, { body: 'I am an attachment' } ] }, function (error, response, body) { if(response.statusCode == 201){ console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand); } else { console.log('error: '+ response.statusCode); console.log(body); } })
Install it via npm, as always:
npm install request
Sponsor this blog series!
Doing a node.js company and want your ad to appear in the series? The ad will go out to 14,000 rss subscribers, 7,000 email subscribers, and it will get viewed by thousands of my blog visitors! Email me and we'll set it up!
See ya!
If you love these articles, subscribe to my blog for more, follow me on Twitter to find about my adventures, and watch me produce code on GitHub!
source : http://www.catonmat.net/blog/nodejs-modules-request/
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· Cursor预测程序员行业倒计时:CTO应做好50%裁员计划
· 想让你多爱自己一些的开源计时器
· 大模型 Token 究竟是啥:图解大模型Token
· 用99元买的服务器搭一套CI/CD系统
· 当职场成战场:降职、阴谋与一场硬碰硬的抗争