Skip to content

Instantly share code, notes, and snippets.

@dave-kennedy
Created June 22, 2017 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dave-kennedy/91714d4d514fa547b9deb35e9e8ee3bd to your computer and use it in GitHub Desktop.
Save dave-kennedy/91714d4d514fa547b9deb35e9e8ee3bd to your computer and use it in GitHub Desktop.
Node scripts
var bl = require('bl'),
http = require('http');
function getResponse(url, callback) {
http.get(url, function (response) {
response.pipe(bl(function (err, data) {
if (err) {
return console.error(err);
}
callback(data.toString());
}));
});
}
getResponse(process.argv[2], function (data) {
console.log(data);
});
var bl = require('bl'),
http = require('http'),
parseurl = require('url').parse;
function getResponse(url, payload, callback) {
var urlParts = parseurl(url),
options = {
hostname: urlParts.hostname,
port: urlParts.port,
path: urlParts.path,
method: 'POST'
};
var request = http.request(options, function (response) {
response.pipe(bl(function (err, data) {
if (err) {
return console.error(err);
}
callback(data.toString());
}));
});
request.write(encodeURIComponent(payload));
request.end();
}
getResponse(process.argv[2], process.argv[3], function (data) {
console.log(data);
});
var fs = require('fs'),
http = require('http'),
path= require('path'),
url = require('url'),
mimeTypes = {
'.css': 'text/css',
'.html': 'text/html',
'.jpeg': 'image/jpeg',
'.jpg': 'image/jpeg',
'.js': 'text/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.txt': 'text/plain'
};
http.createServer(function (request, response) {
console.log(request.method, request.url);
var pathName = url.parse(request.url).pathname,
filePath = path.join(process.cwd(), pathName);
fs.stat(filePath, function (err, stats) {
if (err) {
response.statusCode = 404;
response.setHeader('Content-Type', 'text/plain');
response.write('404 Not Found\n')
response.end();
return;
}
if (!stats.isFile()) {
response.statusCode = 403;
response.setHeader('Content-Type', 'text/plain');
response.write('403 Forbidden\n')
response.end();
return;
}
var fileExt = path.extname(filePath),
mimeType = mimeTypes[fileExt] || 'text/plain';
response.statusCode = 200;
response.setHeader('Content-Type', mimeType);
fs.createReadStream(filePath).pipe(response);
});
}).listen(7654);
console.log('Listening on http://localhost:7654...');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment