gpt4 book ai didi

javascript - 如何正确导入 javascript 函数并将其用于 node.js 脚本?

转载 作者:搜寻专家 更新时间:2023-11-01 00:16:17 25 4
gpt4 key购买 nike

所以我在 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 文件中。

这就是您在 Node 脚本中调用该函数的方式

var date = require('./timeStamp');
date();

关于javascript - 如何正确导入 javascript 函数并将其用于 node.js 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50420158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com