Some helpful Node.js Samples
SetTimeout – When I say go – go ” setTimeout()
setTimeout()
can be used to schedule code execution after a designated amount of milliseconds.
var count = 0; var t = setInterval(function() {
count++;
console.log("Interval of 10 ms, count = " + count);
if (count === 10) {
clearInterval(t);
}
}, 10); setTimeout(function() {
console.log("Timeout at 200 ms");
},200);console.log("Running!");
Create your own Module
let request = require('request'),
api = 'https://api.cryptonator.com/api/ticker/'function getPrice() {
return new Promise((done, err) => {
err('Use One of Our Methods, Please Check API for reference on Methods')
})
}getPrice.getCryptoPrice = ((base, crypto) => {
return new Promise((done, err) => {
if(typeof base === 'undefined' && typeof crypto === 'undefined') {
err(`You forgot to provide Base / Cryptic Currency Name`)
} else {
let cApi = api + crypto + '-' + base
request(cApi, (error, response, body) => {
if(!error && response.statusCode === 200) {
done(JSON.parse(body).ticker)
} else {
err(`Sorry, We couldn't get the Price. ` + error)
}
})
}
})
})getPrice.getBasePrice = ((base, crypto) => {
return new Promise((done, err) => {
if(typeof base === 'undefined' && typeof crypto === 'undefined') {
err('You forgot to provide Base / Cryptic Currency Name')
} else {
let cApi = api + base + '-' + crypto
request(cApi, (error, response, body) => {
if(!error && response.statusCode === 200) {
done(JSON.parse(body).ticker)
} else {
err(`Sorry, We couldn't get the price. ` + error)
}
})
}
})
})module.exports = getPrice
Multipart File Upload in Node.js
var app = require("express")();
var multiparty = require("multiparty");
app.post("/submit", function(httpRequest, httpResponse, next){
var form = new multiparty.Form();
form.on("part", function(part){
if(part.filename)
{
var FormData = require("form-data");
var request = require("request")
var form = new FormData();
form.append("thumbnail", part, {filename: part.filename,contentType: part["content-type"]});
var r = request.post("http://localhost:7070/store", { "headers": {"transfer-encoding": "chunked"} }, function(err, res, body){
httpResponse.send(res);
});
r._form = form
}
})
form.on("error", function(error){
console.log(error);
})
form.parse(httpRequest);
});
app.get("/", function(httpRequest, httpResponse, next){
httpResponse.send("<form action='http://localhost:9090/submit' method='post' enctype='multipart/form-data'><input type='file' name='thumbnail' /><input type='submit' value='Submit' /></form>");
});
app.listen(9090);
Leave a Reply