how print modules on web - javascript

var http = require('http');
function start() {
function onRequest(req, res) {
console.log("Request received.");
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
var procfs = require('procfs-stats');
var ps = procfs(process.pid);
function sysUsage() {
ps.io(function(err, io) {
console.log('My process has done this much io', io);
});
}
exports.sysUsage = sysUsage;
here is my code, I am new in Node.js
how can i print "procfs-stats" and "libCpuUsage" on web?, not in console.
thanks

You need a template engine, there are many (http://garann.github.io/template-chooser/), common ones are:
Jade
EJS
But it's up to you to choose your preferred for your Node application.
Probably the best option for you is to install and use ExpressJS framework in your Node.js app, it gives you a powerful suite of features to be used in your app.
And of course, it gives you a simple way to add a template engine too.
Please refer to this for your specific needs: Using template engines with Express

Related

Questions on to use Node.js as local server with Braintree?

I'm not new to JavaScript but I am new to Node.js and back end languages. I have a very simple question.
I've installed and setup Node.js on my computer and I'm attempting to get a server going between my static files & directory(s) and my browser to be able to send and receive requests. I've downloaded Braintree's free Sandbox (found here) for practice to get some faux transactions going just to gain a better understanding of how this can work.
I set up a local server by running npm install -g http-server on my command line and then http-server to set it up.
I then received the following message in my command line:
Starting up http-server, serving ./public
Available on:
http://127.0.0.1:8080
http://10.0.1.4:8080
Hit CTRL-C to stop the server
So, with this setup...if I wanted to do get() and post() methods and see it rendered and communicating between my "server" and my static files. How do I do this? For example, if I were to set up Braintree's sandboxed environment and then create a clientToken using the following code from Braintree's website
const http = require('http'),
url = require('url'),
fs = require('fs'),
express = require('express'),
braintree = require('braintree');
const gateway = braintree.connect({
environment: braintree.Environment.Sandbox,
merchantId: "xxxxx",
publicKey: "xxxxx",
privateKey: "xxxxx" //blocked out real numbers for privacy
});
Here is the remaining code I hae to create a "client Token" for a transaction...and here is the guide I'm following via Braintree's website...
http.createServer((req,res) => {
gateway.clientToken.generate({
},(err, response) => {
if(err){
throw new Error(err);
}
if(response.success){
var clientToken = response.clientToken
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(clientToken);
res.end("<p>This is the end</p>");
} else {
res.writeHead(500, {'Content-Type': 'text/html'});
res.end('Whoops! Something went wrong.');
}
});
}).listen(8080,'127.0.0.1');
So, my question is...if I wanted to generate send a token to a client using the get() method...how would I do that? Would it have to be a separate js file? How would they be linked? If they're in the same directory will they just see each other?
Here is an example on Braintree's website of how a client token may be sent:
app.get("/client_token", function (req, res) {
gateway.clientToken.generate({}, function (err, response) {
res.send(response.clientToken);
});
});
How could this be integrated into my current code and actually work? I apologize if these are elementary questions, but I would like to gain a better understanding of this. Thanks a lot in advance!
I don't know much about braintree, but usually you would use somthing like express.js to handel stuff like this. So I'll give you some quick examples from an app I have.
#!/usr/bin/env node
var http = require('http');
var app = require('../server.js');
var models = require("../models");
models.sync(function () {
var server = http.createServer(app);
server.listen(4242, function(){
console.log(4242);
});
});
So that's the file that gets everything started. Don't worry about models, its just syncing the db.
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
// share public folder
app.use(express.static(path.join(__dirname, 'public')));
require('./router.js')(app);
module.exports = app;
next up is the server.js that ties eveything together. app.use() lines are for adding middleware and the app.use(logger('dev')); sets the route logger for what your looking for.
app.use(express.static(path.join(__dirname, 'public'))); shares out all files in the public directory and is what your looking for for static files
var path = require('path');
module.exports = function(app){
//catch
app.get('*', function(req, res){
res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});
}
last piece is the router.js. This is were you would put all of you get and post routes. generally I've found that if you see app.get or app.post in examples there talking about express stuff. It's used a lot with node and just makes routing way easier.
Also if your using tokens a route would look like this.
app.get('/print', checkToken, function(req, res){
print.getPrinters(function(err, result){
response(err, result, req, res);
});
});
function checkToken(req, res, next){
models.Tokens.findOne({value: req.headers.token}, function(err, result){
if(err){
res.status(500).send(err);
}else if(result == null){
console.log(req.headers);
res.status(401).send('unauthorized');
}else{
next();
}
});
}
so any route you want to make sure had a token you would just pass that function into it. again models is for db

making js and other files available to html via node.js http server

I have a very simple web server like this:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('./index.html', 'utf-8', function (err, content) {
if (err) {
res.end('something went wrong.');
return;
}
res.end(content);
});
}).listen(8080);
console.log("Server running on port 8080.")
This renders my index.html without any issues, but if I try to reference another file in my index.html via a script tag for instance, the site just gets stuck, unable to find the file which exists in the server directory.
How can I make those files available to my index.html file?
Please keep in mind that I realize this can be done much more easily with Express but I do not wish to use Express. I am trying to learn how things work behind the scene. Thanks in advance.
You need to make the directory visible to public. Its is recommend to use framework while developing the Node.js application.
Here is the code below to server file without framework.
var basePath = __dirname;
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function(req, res) {
var stream = fs.createReadStream(path.join(basePath, req.url));
stream.on('error', function() {
res.writeHead(404);
res.end();
});
stream.pipe(res);
}).listen(9999);
Refer : Node itself can serve static files without express or any other module..?

Are there any http proxy for development which trigger tasks such as preprocess js before app response?

A scenario of mine:
I'd like to convert jsx file (React) into normal js.
And I need browserify or a kind because one of modules needs require.
Watching files for every modifications and repeating tasks make me feel overkill. Those tasks are only needed to be executed on timing of browser reload (on a request).
I know Rails development env does this, but in this case a node.js app.
So I do like to use a http proxy in front of my app and let execute those tasks before my app responses to browser.
Any tools available already? or any advice for implementing such a proxy?
I don't mind if those tools are available already in any language, (node.js, python or ruby), but if non I'd like to implement one with node.js.
While app server is running on port 3000, I wrote a quick and dirty reverse proxy like this.
This proxy listens on port 31000 and just forward every requests, but if path is "/bundle.js" execute a command before forward the request.
var exec = require('child_process').exec;
var http = require('http');
var httpProxy = require('http-proxy')
var proxy = httpProxy.createProxyServer({target: "http://localhost:3000"})
var proxyServer = http.createServer(function(req, res) {
if (req.url == '/bundle.js') {
exec("jsx src/ build/ && browserify build/app.js -o bundle.js", function(err, stdout, stderr) {
if (err) {
console.error('error: ' + err);
}
proxy.web(req, res);
});
} else {
proxy.web(req, res);
}
});
proxyServer.on('upgrade', function (req, socket, head) {
proxy.ws(req, socket, head);
});
proxyServer.listen(3100);

How to write a node express app that serves most local files, but reroutes some to another domain?

I'm working on a small webapp that normally is built with a relatively complex process and then deployed to WebLogic.
However, the portion I'm working on is using AngularJS, and is all HTML and Javascript. It normally makes ajax calls into another webapp on the same domain. To shorten my development cycle, I'd like to avoid a build process and just reload the browser page.
I think I can do this with "node express", but the details escape me. I've managed to define a very simple app that just serves local files, but now I have to figure out how to detect some of those paths as matching an expression, and reroute those requests to a request to an external domain.
So, if it gets a request for "/diag/stuff.html", "/foo/thing.html", or just "/index.html", it will send back the file matching the same path. However, if the path matches "/fooService/.*", then I have to send back the response from a GET to the same path, but on a different host and port.
This is my trivial app so far:
var express = require('express');
var app = express();
app.use("/", express.static(__dirname));
app.listen(8000);
Update:
I like the proxy idea, so I did a local install of "http-proxy" (I forgot and first did a global install) then changed the script to this:
var express = require('express');
var app = express();
var httpProxy = require('http-proxy');
var proxy = new httpProxy.RoutingProxy();
app.use("/", express.static(__dirname));
app.get('/FooService/*', function(req, res) {
"use strict";
return proxy.proxyRequest(req, res, {
host: "foohost.net",
port: 80
});
});
app.listen(8000);
This fails with:
<path>\server.js:4
var proxy = new httpProxy.RoutingProxy();
^
TypeError: undefined is not a function
at Object.<anonymous> (<path>\server.js:4:13)
What might be wrong here?
Update:
Would it be useful to see the contents of "console.log(httpProxy)" after that "require"?:
function ProxyServer(options) {
EE3.call(this);
this.web = this.proxyRequest = createRightProxy('web')(options);
this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options);
this.options = options;
this.webPasses = Object.keys(web).map(function(pass) {
return web[pass];
});
this.wsPasses = Object.keys(ws).map(function(pass) {
return ws[pass];
});
this.on('error', this.onError.bind(this));
}
Does that provide a clue for why "new httpProxy.RoutingProxy()" says it's undefined?
You can use http-proxy and forward requests to different host. To install http-proxy you need to run sudo npm install http-proxy. Code that will handle proxy will look like that:
httpProxy = require('http-proxy');
proxy = new httpProxy.RoutingProxy();
(...)
app.get('/fooService/*', function (request, response) {
"use strict";
return proxy.proxyRequest(request, response, {
host : externalHost,
port : 80
});
});
UPDATE
Above code is working for http-proxy ~0.10.x. Since then lot of things had changed in library. Below you can find example for new version (at time of writing ~1.0.2):
var httpProxy = require('http-proxy'),
proxy = httpProxy.createProxyServer({});
(...)
app.get('/fooService/*', function (request, response) {
"use strict";
return proxy.web(request, response, {
target: 'http://fooservice.com'
});
});
If redirects meet your need, then that's the easiest solution:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(app.router);
app.get('/fooService/*', function(req, res){
res.redirect(302, 'http://otherdomain.com:2222' + req.path);
});
app.listen(8000);
Note that it's generally considered good practice to use a subdirectory for your static files (like public above). Otherwise you could view your app file itself and anything else you keep in your application root!

rendering jade files in expressjs

I have a basic expressjs app (using jade), but I am having trouble rendering basic Jade files. When I get a request, i parse the url for the pathname and use the handle object to route the request as follows:
index.js
var requestHandlers = require('./requestHandlers');
var handle = {};
handle['/'] = requestHandlers.start;
handle['/download'] = requestHandlers.download
requestHandlers.js
function start(res) {
console.log("request handler for start called");
res.render('home', {title: 'express'});
}
function download(res) {
res.render('download', {title: 'download'})
res.end();
}
exports.start = start;
exports.download = download;
home.jade
h1= title
p Welcome to #{title}
I am using Jade as my templating engine, and have configured the server in a seperate server.js file. When i request either of the pages, the title displays correctly on my browser tab, but the page doesn't display, it just keeps loading. Weirdly, when I cancel the request the page displays. It's as if everything works but nothing tells the process to end?
I am relatively new to node so excuse my naiveté on any of the above. Let me know if there are any questions I can clear up.
I'm not 100% positive why your code isn't killing the TCP connection as needed to prevent your browser from timing out, but I can provide a solution that is friendly towards Express conventions that should solve your issues and maintain code readability, maintainability, and separation.
./app.js (your main server script)
var express = require('express'),
app = express.createServer(),
routes = require('./routes');
app.configure(function () {
// Render .jade files found in the ./views folder
// I believe you are already doing this
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// Use the built-in Express router
// This kills the "handle" method you had implemented
app.use(app.router);
// Client-side assets will be served from a separate ./public folder
// i.e. http://yourhost.com/js/main.js will link to ./public/js/main.js
app.use(express.static(__dirname + '/public'));
});
// Initialize routes
routes.init(app);
./routes/index.js
exports.init = function (app) {
app.get('/', function (req, res) {
console.log("request handler for start called");
// Render __dirname/views/home.jade
res.render('home', {title: 'express'});
});
app.get('/download', function (req, res) {
// Render __dirname/views/download.jade
res.render('download', {title: 'download'})
});
});
The above prevents you from needing to parse the URL parameters by yourself. Also you can define more readable and powerful request handlers (i.e. app.post for POST methods). You are now enabled to more easily tie in things like the Express-Resource module if you decide to build a REST API.
If you need more powerful mappings you can use regular expressions in the first parameter of app.[get/post/put/del] to filter for specific paths instead.

Categories