[英]How to correctly import javascript function and use it into a node.js script?
所以我在一個 javascript 文件中有一個時間戳函數,它返回一個看起來像MM/DD/YY
我想將函數返回的內容導入另一個腳本(node.js)並在腳本運行時顯示它。
但是每當我啟動 node.js 程序時,我都會得到類似的信息: [object Object]
,我不知道這是從哪里來的......
這是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;
}
這是node.js
腳本
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);
});
});
我該如何修復這個錯誤或者我做錯了什么或遺漏了什么?
您需要將timeStamp
函數添加到exports
對象,然后您就可以在任何您想要的文件中使用它。 這就是你這樣做的方式
module.exports = timeStamp;
在您的timeStamp.js
文件中。
這就是您在節點腳本中調用該函數的方式
var date = require('./timeStamp');
date();
添加module.exports = timeStamp;
到 timeStamp.js 文件,然后您需要在console.log('Date is ...'+date() );
陳述。
你錯過了: module.exports = timeStamp;
沒有它,當使用require
時將導出一個空對象,這就是為什么你得到 [Object object]
console.log('Date is...' + {});
除此之外,您將需要調用日期函數,否則您將打印實際的函數代碼。
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.