Node.js. Error: module is not a function - javascript

i have a main file -- index.js:
var express = require('express');
var app = express();
var request = require('request');
var demo = require('demo');
// This app will only respond requests to the '/scrape' URL at port 3000.
app.get('/scrape', function (req, res) {
var url = "http://www.l.com";
request(url, function (error, response, html) { // two parameters: an URL and a callback
if (!error) {
demo(html);
}
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
and my module is demo.js:
module.exports = function (html) {
....
return JSON.stringify(json);
}
The error is :
TypeError: demo is not a function
I am new to node.js, i would like to know why this didn't work. Maybe i dont understand the real principle of module?
Thank you for answer me first.

You're not exporting your module properly. It should be:
exports.demo = function ....

Try to include your demo module in index.js:
var demo = require('./demo.js');

For the other freshers who use module in node.js for the first time.
first, made a new module called the name of your module.js
Second, it is not necessary to do "
npm install demo --save", if you want, it is also okay.
Third, in the main js which u want to call this module, focus on the name and the path of the module, you should write var anyName = require('the name of your module');, if they are in the same directory, you should write like this: var anyName = require('./the name of your module');

Related

Using functions outside module exports

I'm trying to do my best to explain what I'm trying to do, please let me know if something wasn't understandable.
I have a file called www where I'm setting up my socket like that
var server = http.createServer(app);
var io = require('socket.io')(server);
require('../store.js')(io);
I'm sending the io data to another file to use it properly. To capture the io I'm using.
module.exports = function (io){
}
What I'm trying to do is how could I use the io outside from the module.exports in the store.js file? I've tried to create a variable and then use it, but that doesn't seem to work.
Example how I've tried it.
var ioData;
ioData.on('connection', function(socket) {
//Doesn't work
});
module.exports = function(io){
ioData = io;
}
you can do this
store.js
const store = {
io: {},
setIo(io) {
store.io = io;
},
setHandlers() {
store.io.on('connection', function(socket) {
// do something with connected socket
});
}
};
module.exports = store;
www
var server = http.createServer(app);
var store = require('../store');
var io = require('socket.io')(server);
store.setIo(io);
store.setHandlers(io);
You need to create a add the connection event handler into the module export function, since when you change ioData, it doesn't re-add the handler.
var ioData;
module.exports = function(io){
ioData = io;
ioData.on('connection', function(socket) {
//Doesn't work
});
}

issue child process inside a server on node.js

I have an executable library in C (sudo ./ads1256_test adc.txt) where data are acquired from an ADC, likewise these data are automatically save in a text file (adc.txt).
On the other hand, I have a server in node.js (see code) in which would like to execute this program when a button in the website is pressed. For this, I tried to implement this process using the child process .exec('sudo ./ads1256_test adc.txt') but it did not work. It apparently runs but the values saved in the file are always zero. That is totally different to the obtained result when I execute the same command in terminal. I would appreciate if anybody could help me.
//Importing the core modules
var express = require('express');
var path = require('path');
var sys = require('sys');
var fs = require('fs');
var util = require('util');
var sleep = require('sleep');
var app = express();
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
app.get('/', function(req,res){
res.sendFile(path.join(__dirname + '/public/index.html'));
});
//Static Directories
app.use(express.static(__dirname + '/public'));
app.post('/test', function (req, res) {
exec('sudo ./ads1256_test adc.txt');
});
//Server Starting
var server = app.listen(8080, function(err){
if(err){
console.log('Error starting http server');
} else{
console.log('Sever running at http://localhost:8080 ');
}
});
first thing first, fix your code to
- asynchronously handle the cp spawn
- show errors
Example with tree, may you adapt it to your binary and check the response, it should help you go forward.
app.post('/test', function (req, res) {
var cp = spawn('tree', []);
cp.stdout.pipe(res);
cp.stderr.pipe(res);
cp.on('close', function () {
res.end();
cp.stdout.unpipe();
cp.stderr.unpipe();
});
});

(crypto.js) TypeError: Data must be string or buffer

I am currently using crypto.js module to hash things. It was working for a while then I started getting this error:
Here is the foundation of my server:
process.stdout.write('\033c'); // Clear the console on startup
var
express = require("express"),
app = express(),
http = require("http").Server(app),
io = require("socket.io")(http),
path = require("path"),
colorworks = require("colorworks").create(),
fs = require("fs"),
crypto = require("crypto");
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
http.listen(443, function(){
// Create the http server so it can be accessed via 127.0.0.1:443 in a web browser.
console.log("NJ project webserver is running on port 443.");
// Notify the console that the server is up and running
});
app.use(express.static(__dirname + "/public"));
app.get("/", function(request, response){
response.sendFile(__dirname + "/public/index.html");
});
I am aware that these functions are creating the problem:
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
The problem being, if these functions don't work (which they don't anymore), roughly 200 lines of code will go to waste.
This error is triggered by attempting to hash a variable that does not exist:
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
md5(non_existent); // This variable does not exist.
What kind of data are you trying to hash ? Where does it come from ?
I would check the value of msg first then I would try :
crypto.createHash('md5').update(msg.toString()).digest('hex');
You could also use these packages instead:
https://www.npmjs.com/package/md5
https://www.npmjs.com/package/js-sha256

How do you use a Node.js variable on the client-side?

I'm relative new to NODEJS and I'm struggling with a basic problem, which is the correct use of global variables, I read a lot about it but it seems I can't make it work properly, I'll post some codes for a better view of the problem.
I have this simple js running as a server:
myapi.js
var http = require('http');
var express = require('express');
var app = express();
var exec = require('child_process').exec, child;
var fs = require('fs');
var jUptime;
var ipExp = require('./getDown');
var filesD = [];
var path = "/media/pi/01D16F03D7563070/movies";
app.use(express['static'](__dirname ));
exec("sudo /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'", function(error, stdout, stderr){
ip = stdout;
exports.ipAdd = ip;
console.log(ip);
});
app.get('/files', function(req, res) {
fs.readdir(path, function(err, files) {
if (err){
console.log("Non riesco a leggere i files");
}
filesD=files;
console.log(filesD);
});
res.status(200).send(filesD);
});
app.get('/up', function(req, res) {
child = exec("uptime -p", function(error, stdout, stderr){
jUptime = [{uptime: stdout}];
});
res.status(200).send(jUptime);
});
app.get('*', function(req, res) {
res.status(404).send('Richiesta non riconosciuta');
});
app.use(function(err, req, res, next) {
if (req.xhr) {
res.status(500).send('Qualcosa รจ andato storto');
} else {
next(err);
}
});
app.listen(3000);
console.log('Server attivo sulla porta 3000');
And then I have this JS used in a simple web page:
getDown.js
var ip = require('./myapi').ipAdd;
function gDownloads() {
var url;
var jqxhr;
var dat;
url = 'http://' + ip + '/files';
jqxhr = $.getJSON(url, function(dat) {
for(i=0; i<dat.length; i++){
$('#downLoad').append('<p>' + dat[i] + '</p>');
}
$('#bId').append(dat.length);
})
.done(function() {
console.log("OK");
})
.fail(function(data) {
console.log("Fallito: "+data);
})
};
The problem is that when I navigate to the html page that use getDown.js I get the following error on getDown.js
require is not defined
I need to pass the variable that contains the IP address in myapi.js to use it in getDown.js, I hope I explain myself good enough, thanks in advance.
require is global that exists in Node.js code, that is, on the javascript code executing in the server.
Your server will respond to the client and give it an HTML page to render. That HTML page could tell the browser to also request a javascript file from the server. When it receives that file, the client will execute it. The client does not have a require global (you can test it by opening up the console and typing require)
Using Browserify
Or you can write Node-style code, requiring your global like you're doing, but then run the code through browserify. This will create a new javascript bundle that can be executed by the client, so you should tell your html page to use that bundle instead of getDown.js.
Here is a basic example of doing using browserify like this.
module.js
function getIp() {
return 123456;
}
module.exports = {
getIp: getIp
};
main.js
var module = require('./module');
function getIp() {
var ip = module.getIp();
return ip;
};
console.log(getIp());
compile bundle
$ browserify main.js -o public/bundle.js
index.html
<script type="text/javascript" src="public/bundle.js"></script>
Global variable on the client
To use a global variable on the client which is known by the server, you can pass that variable to your rendering engine (possibly Jade if you're using Express) and have it interpolate that variable into a <script> tag which defines some globals. Leave a comment if that's the approach you'd prefer and I can add some more details.
Let me know if you have more questions!

middleware not working on connect HTTP server

I am reading Professional Node.js and i'm trying to understand connect HTTP middleware framework. I created a simple middleware that returns a function that replies with a custom test string:
function replyText(text) {
return function(req, res) {
res.end(text);
};
}
module.exports = replyText;
But when i try to use this middleware in a connect server. Node gives me an error:
/Users/socomo22/work/hello_world_app_v2.js:8
var app = connect.createServer(replyText('Hello World!'));
^
TypeError: undefined is not a function
But when i simply use:
var app = connect();
app.listen(8080)
It runs without giving any error. I don't understand whether i'm doing any syntatical mistake. How would i use this simple middleware? This is my connect server file:
var connect = require('connect');
// middlewares
var replyText = require('./reply_text');
var app = connect();
var app = connect.createServer(replyText('Hello World!'));
app.listen(8080, function() {
console.log('listening on 8080 port')
});
As pointed by documentation use use API to mount a middleware and a http module to create an instance of server although you can create an instance just with connect as pointed here.
As pointed by #FranciscoPresencia adding .js extension while you require a your local module is optional.
var replyText = require('./reply_text.js');
So your code should look like this and i tested it. Working as intended
var connect = require('connect')
var http = require('http')
var app = connect();
// middlewares
var replyText = require('./reply_text.js');
app.use(replyText('Hello World!'));
http.createServer(app).listen(8080, function() {
console.log('listening on 8080 port')
});
Note: Try to avoid ports like 8080, 80 etc as its a reserved ports that might be used by other apps. This sometimes may cause node to fail.
Adding the output screenshot for your reference
Here You can start server in this way...
var connect = require('connect');
var http = require('http');
var app = connect();
var replyIN = require('./connetFile.js')
app.use(replyIN('Hello there m back again'));
http.createServer(app).listen(8888,function(){console.log('Server has started');});
And this is your connectFile.js
function replyIN(text){
return function (req, res) {
res.end(text);
};
};
module.exports = replyIN;

Categories