so I have a time-stamp function in a javascript file that return a date that look like MM/DD/YY
I would like tom import what the function return into another script ( node.js) and display it whenever the script run.
But whenever I fire up the node.js program , I get something like : [object Object]
, and I have no idea where this comes from ...
Here is the timeStamp.js
function timeStamp() {
let now = new Date();
let date = [ now.getMonth() + 1, now.getDate(), now.getFullYear() ];
let time = [ now.getHours(), now.getMinutes(), now.getSeconds() ];
let suffix = ( time[0] < 12 ) ? "AM" : "PM";
time[0] = ( time[0] < 12 ) ? time[0] : time[0] - 12;
time[0] = time[0] || 12;
for ( var i = 1; i < 3; i++ ) {
if ( time[i] < 10 ) {
time[i] = "0" + time[i];
}
}
return date.join("/") + " " + time.join(":") + " " + suffix;
}
and here is the node.js
script
let io = require('socket.io').listen(process.env.port||5000);
var date = require('./timeStamp');
io.on('connection', function(socket) {
console.log('Date is ...'+date);
socket.on('data',function (data , callback) {
console.log(`"${data}" was received ...`);
callback(true);
});
});
How can I fix this bug or what am I doing wrong or missing ?
You need to add timeStamp
function to exports
object then you'll be able to require it in any file you want. And this is how you do that
module.exports = timeStamp;
in your timeStamp.js
file.
And this is how you'll call that function in your node script
var date = require('./timeStamp');
date();
add module.exports = timeStamp;
to the timeStamp.js file, and then you'll need to do date() in the console.log('Date is ...'+date() );
statement.
You're missing: module.exports = timeStamp;
without it, when using require
an empty object will be exported, that's why you get [Object object]
console.log('Date is...' + {});
Apart from that, you will need to call the date function, otherwise you will print the actual function code.
console.log('Date is...' + date());
function timeStamp() { let now = new Date(); let date = [ now.getMonth() + 1, now.getDate(), now.getFullYear() ]; let time = [ now.getHours(), now.getMinutes(), now.getSeconds() ]; let suffix = ( time[0] < 12 ) ? "AM" : "PM"; time[0] = ( time[0] < 12 ) ? time[0] : time[0] - 12; time[0] = time[0] || 12; for ( var i = 1; i < 3; i++ ) { if ( time[i] < 10 ) { time[i] = "0" + time[i]; } } return date.join("/") + " " + time.join(":") + " " + suffix; } // In node use module.exports here // module.exports = timeStamp; // This will print the function code console.log('Date is...' + timeStamp); // This will print the correct date console.log('Date is...' + timeStamp());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.