繁体   English   中英

如何正确导入 javascript 函数并将其使用到 node.js 脚本中?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM