How to add a callback in this function for gzip - javascript

Here is my code:
/*jshint globalstrict: true*/
var zlib = require('zlib');
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'});
var text = "Hey this works!";
zlib.gzip(text, function (_, result) {
res.end(result);
});
}).listen(8081);
I want to add a callback to the above code to follow the node.js async concept. How do I do that? Also, I am pretty new to node.js

var callback = function (err, result) {
// gzip has finished, do any thing you want here,
// also add if about the 'err' as mscdex said.
res.end(result);
}
zlib.gzip(text, callback);
callback is a function,you already added it .

Related

How to save data from JSON to a variable in NodeJS

I'm new in Node.js, I have a problem.
I would like to save data from JSON object which I have downloaded from github API.
var http = require("http");
var express = require('express');
var app = express();
var github = require('octonode');
var client = github.client();
app.set('port', process.env.PORT || 8000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
app.get('/getUsers', function (req, response) {
response.writeHead(200, {'Content-Type': 'text/json'});
var result;
client.get('/users/angular/repos', {}, function (err, status, body, headers) {
result = response.write(JSON.stringify(body));
console.log(result); //JSON object
return result;
});
console.log(result); //undefined
});
How can I save an data from object to single variable?
(I want to then transform it to an Array and take some useful data).
You will not get result outside of the asynchronous call as it is not yet defined. To get this value either call a method inside the callback of query or use async module and pass it.
app.get('/getUsers', function (req, response) {
response.writeHead(200, {'Content-Type': 'text/json'});
var result;
client.get('/users/angular/repos', {}, function (err, status, body, headers) {
result = response.write(JSON.stringify(body));
console.log(result); //JSON object
doSomeOperationOnResult(result)
});
});
function doSomeOperationOnResult(result){
//Your operating code
}

how to run different .js file in one server.js file in NODE JS?

this is demo.js file and i want to use this file in server.js file so that i can use diffrent js files in one server file.
Demo.js:
app.get('/add User', function (req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/project';
MongoClient.connect(url, function (err, db) {
var collection = db.collection('users');
collection.find({name: 'shruti'}).toArray(function (err, result) {
console.log(, result);
db.close();
});
Server.js:
var a = require('./demo.js');
vr http=require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(a);
res.end();});
server.listen(7860);
A possible sample would look like :
demo.js
var myModule = {
defineRoutes: function(router){
//do something...
}
}
module.exports = myModule;
server.js
var myModule = require('demo.js');
myModule.defineRoutes(router);
As stated, you need to export.
When you do:
var item = require("mymodule");
Require returns an object, which is a reference the value of module.exports for that given file - in your case demo.js.
You can write your modules a few ways as some people have shown you. Because it is encapsulated you basically are identifying what is public or can be called. Few ways to write it - you could also do:
module.exports = {
yourCall: function () {
console.log("stuff here");
}
};
As stated by #ishann, who is dead on here, you are writing something you assume might be populated. Going to a database and returning is an asynchronous call - so it will take time to go do that and then for the results to be returned.
Based on your structure - ideally what you want to do is assign the route ( "/addUser" ) which will pass in the response object to you:
app.get('/add User', function (req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/project';
MongoClient.connect(url, function (err, db) {
var collection = db.collection('users');
collection.find({name: 'shruti'}).toArray(function (err, result) {
console.log(, result);
db.close();
// set the type
res.writeHead(200, {"Content-Type": "application/json"});
res.write(result);
});
Just looks like your code needs a bit of reorg, but separting concerns is good. You might want to also check out Express as a framework for node.

NodeJS throw new TypeError

When i try to run my JS file i get this error:
http.js:783
throw new TypeError('first argument must be a string or Buffer');
I was following this tutorial which didn't seem to mention the problem Tutorial Link
My JS file has:
var http = require('http'),
fs = require('fs'),
sanitize = require('validator').sanitize;
var app = http.createServer(function (request, response) {
fs.readFile("client.html", 'utf-8', function (error, data) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
});
}).listen(1337);
var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
socket.on('message_to_server', function(data) {
var escaped_message = sanitize(data["message"]).escape();
io.sockets.emit("message_to_client",{ message: escaped_message });
});
});
I have Socket.io and validator installed in my node_modules folder. I'm quite new to this sort of stuff and looks like this tutorial wasn't a good starting choice, I can't seem to get it working.
You're not doing any error checking, and I'd bet that readFile is throwing an error. This means data is undefined, so when you try to response.write(data), the http module throws an error.
Always check the error parameter in your callback functions, and handle it appropriately.
fs.readFile("client.html", 'utf-8', function (error, data) {
if (error) {
response.writeHead(500, {'Content-Type': 'text/html'});
response.write(error.toString());
} else {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
}
response.end();
});

How do I compile jade on request rather than just server start?

I'm looking to compile my jade on server request/response that way I can make changes to the jade file and see it in real time, rather than having to restart the server every time. This is the fake mockup I have so far.
var http = require('http')
, jade = require('jade')
, path = __dirname + '/index.jade'
, str = require('fs').readFileSync(path, 'utf8');
function onRequest(req, res) {
req({
var fn = jade.compile(str, { filename: path, pretty: true});
});
res.writeHead(200, {
"Content-Type": "text/html"
});
res.write(fn());
res.end();
}
http.createServer(onRequest).listen(4000);
console.log('Server started.');
I hope I made myself clear!
You're only reading the file once, on server startup. If you wanted to have it read changes you'd have to read it on request, meaning your mock-up would look more like:
function onRequest(req, res) {
res.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile(path, 'utf8', function (err, str) {
var fn = jade.compile(str, { filename: path, pretty: true});
res.write(fn());
res.end();
});
}
Something like that would read the file every time, which is probably okay for development purposes, but if you only wanted to reload/process the file when something changed, you might use a file watcher (fs.watch might fit this bill).
Something like this (just an untested example as an idea):
var fn;
// Clear the fn when the file is changed
// (I don't have much experience with `watch`, so you might want to
// respond differently depending on the event triggered)
fs.watch(path, function (event) {
fn = null;
});
function onRequest(req, res) {
res.writeHead(200, {
"Content-Type": "text/html"
});
var end = function (tmpl) {
res.write(tmpl());
res.end();
};
if (fn) return end(fn);
fs.readFile(path, 'utf8', function (err, str) {
fn = jade.compile(str, { filename: path, pretty: true});
end(fn);
});
}

Simple server on node js

Hello all :) My problem is that is not working response.vrite ()
Why ?
And another question. Will be called db.open each boot / upgrade page?
var http = require("http");
var Db = require ("mongodb").Db;
var Server = require("mongodb").Server;
function start () {
'use strict';
function onRequest (request, response) {
'use strict';
var db = new Db ("TestApp", new Server ("127.0.0.1", 27017, {}));
response.writeHead(200, {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"});
db.open (function (err, db, response) {
db.collection ('ObjectCollection', function (err, collection) {
collection.find().toArray (function (err, docs) {
console.log (docs);
response.write(JSON.stringify(docs));
});
});
});
response.end();
}
http.createServer(onRequest).listen(8080);
console.log ('Server has started...')
}exports.start = start;
You're calling response.end before your response.write. Move the response.end call inside the callbacks like this:
var http = require("http");
var Db = require ("mongodb").Db;
var Server = require("mongodb").Server;
function start () {
'use strict';
function onRequest (request, response) {
'use strict';
var db = new Db ("TestApp", new Server ("127.0.0.1", 27017, {}));
response.writeHead(200, {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"});
db.open (function (err, db, response) {
db.collection ('ObjectCollection', function (err, collection) {
collection.find().toArray (function (err, docs) {
console.log (docs);
response.write(JSON.stringify(docs));
response.end();
});
});
});
}
http.createServer(onRequest).listen(8080);
console.log ('Server has started...')
}
exports.start = start;
And yes, a new Db object will be opened on each request so it would be better to open that once during startup.
Like Johnny said, your calling response.end() outside of your asynchronous functionality. As a rule, you should never count on callbacks actually executing in a blocking manner unless you KNOW how their parent function works under the hood. DB.open likely runs that callback upon connection completion, and we don't know how long that will take. Since DB.Open is non-blocking, node then executes the response.end before DB.open's asynchronous call to the database likely even completes. You may want to read up a bit on asynchronous javascript

Categories