Im using node JS aplication and I've created new js file with module and In this module I export just one function,in this module lets say I've additional two functions for internal use only and should not be exposed outside, each function use different require modules like following:
module.exports = function (app, express) {
var bodyParser = require('body-parser'),
url = require('url'),
http = require('http');
.....
};
function prRequest(req, res) {
httpProxy = require('http-proxy');
....
}
function postRequest(req, res) {
url = require('url');
....
}
My question is from best practice where should I put the require (for url http etc)
1.inside every function that need it?in my case internal and external
2.globally in the file that every function can use?
3.if two is not OK where should I put the require URL which I should use in two functions?better to put in both function or in global or it doesn't matter
The modules should be exposed outside the functions as calling require each time the function is called adds extra overhead. Compare:
const url = require('url');
const start = Date.now();
for (let i = 0; i < 10000000; i++) {
url.parse('http://stockexchange.com');
}
console.log(Date.now() - start);
to:
const start = Date.now();
for (let i = 0; i < 10000000; i++) {
require('url').parse('http://stackexchange.com');
}
console.log(Date.now() - start);
On my machine, the former takes 95.641 seconds to finish executing, while the latter takes 125.094 seconds. Even if you export the function that uses the required module, it will still have access to other variables within its file when imported. So I would declare the modules locally in each file where they're needed, and not globally.
Edit: this would mean you'd want to do this instead:
var bodyParser = require('body-parser'),
url = require('url'),
http = require('http');
module.exports = function (app, express) {
....
};
var httpProxy = require('http-proxy');
function prRequest(req, res) {
...
}
Related
I have this 2 files:
APP.js:
const Request = require('request');
const YVideo = require('./classes/YVideo');
const yvideo = new YTVideo();
YVideo.js:
class YVideo {
constructor(uuid){
this.uuid = uuid;
this.url = 'https://example.com/get_video_info?uuid=';
Request.get(this.url+this.uuid, function(err, resp, body){
this.data = body.split('&');
});
console.log(this.data);
}
}
exports = module.exports = YTVideo;
The code runs until "Request.get(...)". Console shows this error:
"ReferenceError: Request is not defined".
Now, I'm new with Node.js, so what I ask is: Should I require the same module each time for all .js where I use it or there's a way to require it once for entire app?
Question: Should I require the same module each time for all .js where I use it
or there's a way to require it once for entire app?
require locally loads each module, so you will have to use require in every .js file you need the module.
From https://www.w3resource.com/node.js/nodejs-global-object.php
The require() function is a built-in function, and used to include
other modules that exist in separate files, a string specifying the
module to load. It accepts a single argument. It is not global but
rather local to each module.
It has to be required in all the files where you need it. So add it in YVideo file where it is needed.
const Request = require('request');
class YVideo {
constructor(uuid){
this.uuid = uuid;
this.url = 'https://example.com/get_video_info?uuid=';
Request.get(this.url+this.uuid, function(err, resp, body){
this.data = body.split('&');
});
console.log(this.data);
}
}
exports = module.exports = YTVideo;
I have a nodejs route where I am trying to download a url as mp3 using npm-youtube-dl. I have a download directory that I watch with chokidar for files being added and when a file is added I save the link to the file and after the download finishes I call a function that's supposed to respond with the download URL using res.download. When the sendURL function is called the url that I can clearly see has been saved before is undefined when I console.log it... Any idea what i'm doing wrong here/how I can fix this? i'm guessing it's a js variable scope issue?
my code:
var express = require('express');
var router = express.Router();
var yt = require('youtube-dl');
var fs = require('fs');
var path = require('path');
var chokidar = require('chokidar');
var downloadPath = '';
var watcher = chokidar.watch('./downloads', {
ignored: '/^[^.]+$|\.(?!(part)$)([^.]+$)/',
persistent: true
});
watcher.on('add', function(path) {
console.log('added: ', path);
this.downloadPath = path;
console.log('saved', this.downloadPath);
});
/*
router.get('/', function(req, res, next) {
next();
});
*/
router.get('/', function(req, res) {
var url = 'https://soundcloud.com/astral-flowers-music/bella-flor';
var options = ['-x', '--audio-format', 'mp3', '-o', './downloads/%(title)s.%(ext)s'];
var video = yt.exec(url, options, {}, function exec(err, output) {
if (err) { throw err; }
console.log(output.join('\n'));
sendUrl();
});
function sendUrl() {
console.log(this.downloadPath);
//res.download(this.downloadPath);
}
});
module.exports = router;
You're misusing this. If you want to use the downloadPath variable in your functions, remove the this. from in front of them. this.downloadPath looks for a property called downloadPath on an object referenced by this, which is different from your module-global variable.
More: How does the "this" keyword work?
Even with that, you're relying on your add callback having been called before any client requests your / route, and you're returning the last value assigned to downloadPath by that add callback. I don't know enough about what you're doing to know whether that's correct, but the lack of coordination seems problematic.
I am trying to export Connectas an middleware for an HTTP server test, but when I execute the code, it says the follow :
connect.createServer is not a function
My code :
hello_world.js
function helloWorld(req, res) {
res.end('Hello World!');
}
module.exports = helloWorld;
hello_world_app (where the problem is) :
var connect = require('connect');
// import middlewares
var helloWorld = require('./hello_world');
var app = connect.createServer(helloWorld);
app.listen(8080);
He points out to the hello_world_app in the var app, saying that is not a function. How can I make this work ?
Looking at the docs for connect https://www.npmjs.com/package/connect - You are using it incorrectly
You would want something like this:
var connect = require('connect');
var helloWorld = require('./hello_world');
var http = require('http');
var app = connect();
app.use(helloWorld);
http.createServer(app).listen(8080);
Connect doesn't have a function called createServer which is why your code is erroring, that function exists in the http module.
You still need to create the http server with server with the http module. The 'connect' library just helps you use middleware more easily, so you have to plug the middleware into that.
var connect = require('connect');
// import middlewares
var helloWorld = require('./hello_world');
// Initiate the framework
var app = connect();
// Plug in your middleware
app.use(helloWorld);
// Tell http to use the framework
http.createServer(app).listen(8080);
The connect documentation states that you use it this way:
var connect = require('connect');
var http = require('http');
var app = connect();
http.createServer(app).listen(3000);
https://www.npmjs.com/package/connect
I have following nodejs code running on the server (chat engine). I want to convert this into a secure SSL/TLS based connection. How do i do that ?
In the client side (see below code), everytime i tried to convert this into SSL it gives me a error of "Cross origin request failed." i dont know why ?
NODE.JS Server Side Code
var cluster = require('cluster');
var net = require('net');
var fs = require('fs');
var config = require('./config.js');
var num_processes = 1;//require('os').cpus().length;
if (cluster.isMaster) {
// This stores our workers. We need to keep them to be able to reference
// them based on source IP address. It's also useful for auto-restart,
// for example.
var workers = [];
// Helper function for spawning worker at index 'i'.
var spawn = function (i) {
workers[i] = cluster.fork();
// Optional: Restart worker on exit
workers[i].on('exit', function (worker, code, signal) {
if (config.server.restart_instances_on_crash) {
spawn(i);
logging.log('debug', 'Node instances exited, respawning...');
}
});
};
// Spawn workers.
for (var i = 0; i < num_processes; i++) {
spawn(i);
}
// Helper function for getting a worker index based on IP address.
var worker_index = function (ip, len) {
var s = '';
for (var i = 0, _len = ip.length; i < _len; i++) {
if (ip[i] !== '.') {
s += ip[i];
}
}
return Number(s) % len;
};
/* wait 5 seconds to make sure all the instances are running and initialized */
setTimeout(function () {
// Create the outside facing server listening on our port.
var options = {
pauseOnConnect: true
};
var server = net.createServer(options, function (connection) {
// We received a connection and need to pass it to the appropriate
// worker. Get the worker for this connection's source IP and pass
// it the connection.
var str = connection.remoteAddress;
var ip = str.replace("::ffff:", '');
var worker = workers[worker_index(ip, num_processes)];
worker.send('sticky-session:connection', connection);
}).listen(config.server.listenport);
logging.log('debug', 'Server listening on ' + config.server.listenip + ':' + config.server.listenport + '...');
}, 5000);
process.on('uncaughtException', function (error) {
logging.log('error', 'uncaughtException');
logging.log('error',error.stack);
process.exit(1);
});
} else {
var express = require('express');
var sio = require('socket.io');
var sio_redis = require('socket.io-redis');
var dateandtime = require('./includes/dateandtime.js');
var stats = require('./includes/stats.js');
var helper = require('./includes/helper.js');
// Note we don't use a port here because the master listens on it for us.
var app = new express();
// Don't expose our internal server to the outside.
var server = app.listen(0, 'localhost'),
io = sio(server);
io.set('origins', '*:*');
}
In my Client side i have following code based socket.io JS module. (All these works fine without the SSL connection when using net module only)
Following is the client side javascript code to connect to the node server using socket.io functions.
var root_url = 'http://'+window.location.hostname;
var socket_io = 'http://example.com/js/chat/socket.io-1.3.5.js';
$(document).ready(function () {
$.getScript(socket_io, function () {
socket = io.connect(root_url + ':8440');
... etc
Can only hint you into checking the cors package for crossdomain requests but the deeper issue could be that not everything is running in SSL. (mixed http & https)
I am using node.js (v4.2.2) with express (4.13.1). I am trying to import my custom module functions to another module. Application is created with express, and only thing added to app.js is require for my route var tests = require('./routes/tests'); and app.use for that route app.use('/tests', tests);
My two custom files (modules) are (path is relative to project root):
./model/test.js
./routes/tests.js
Here is ./model/test.js:
var id;
var testNumber1;
var testNumber2;
function Test(id, testNumber1, testNumber2) {
this.id = id;
this.testNumber1 = testNumber1;
this.testNumber2 = testNumber2;
};
exports.reset = function() {
this.testNumber1 = 0;
this.testNumber2 = 0;
};
module.exports = Test;
And here is ./routes/tests.js:
var express = require('express');
var Red = require('../model/test.js');
var router = express.Router();
/*create new test :id*/
router.post('/:id', function(req, res, next) {
var myNewTest = new Red(req.params.id, 0, 0)
myNewTest.testNumber2 += 1;
myNewTest.reset();
res.send('id: ' + myNewTest.id +
' testNumber2: ' + myNewTest.testNumber2);
});
module.exports = router;
When I try to execute curl -X POST http://localhost:3000/tests/1 i get error TypeError: myNewTest.reset is not a function. I am having trouble understanding how to export functions correctly. If I understand this api reference correctly, to expose constructor of module, i have to use module.exports = Test;, but that doesn't expose reset function. So, to expose it I have declared it like exports.reset = function() {...}, but obviously, that doesn't work, at least not in my case.
Through some other answers I have also seen function being declared normally function reset() {...}, and exposed like exports.reset = reset;, which gives me the same error.
How do I expose reset function properly?
You should add it to the prototype, at the moment it's just a static method in your module, not attached to the Test constructor.
function Test(id, testNumber1, testNumber2) {
this.id = id;
this.testNumber1 = testNumber1;
this.testNumber2 = testNumber2;
};
Test.prototype.reset = function() {
this.testNumber1 = 0;
this.testNumber2 = 0;
};
module.exports = Test;