我有两个文件,一个位于1.js之间,另一个是import.js。 在between1.js中,我只有几个功能,而其中一个功能已移至import.js。我得到的练习是使用模块并需要功能。我仍然有如何在between1.js中使用require的问题。参见下面的代码
Between1.js代码: https://codeshare.io/alxMvY
import.js: https://codeshare.io/244yg4
我是js和node的初学者。我在import.js中获得了函数,并且在代码底部是module.exports,这意味着要导出模块,并且在1.js之间的第二个文件中,我尝试首先导入该函数: 让utils = require(“ ./ import.js”); 在底部尝试获取功能,但是问题是我真的不知道如何。我试图像在代码中粘贴之前一样,但这没用
我想要的是有人帮助我解释如何要求和模块工作。
import.js代码:
/**
* Module.
*
* Matteus Urbaniak
*/
"use strict";
function teacherAsTable(res) {
let str;
str = "+-----------+---------------------+-----------+----------+--------------+\n";
str += "| Akronym | Namn | Avdelning | Lön | Kompetens |\n";
str += "|-----------|---------------------|-----------|----------|--------------|\n";
for (const row of res) {
str += "| ";
str += row.akronym.padEnd(10);
str += "| ";
str += (row.fornamn + " " + row.efternamn).padEnd(20);
str += "| ";
str += row.avdelning.padEnd(10);
str += "| ";
str += row.lon.toString().padStart(9);
str += "| ";
str += row.kompetens.toString().padEnd(12);
str += " |\n";
}
str += "+-----------+---------------------+-----------+----------+--------------|\n";
return str;
}
module.exports = {
"teacherAsTable": teacherAsTable
};
between1.js
/**
Arbete gjordes av Matteus Urbaniak
*/
"use strict";
/**
Jag använder programmeringsstilen med async/await
för att hantera asynkrona anrop. För det syftet väljer
jag paketet promise-mysql som är en wrapper kring paketet mysql.
*/
const mysql = require("promise-mysql");
// Inloggningsdetaljer till databasen.
const config = require("./config.json");
let utils = require("./import.js");
// Läsa från komand linje
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
/**
Main function
*/
(async function() {
const db = await mysql.createConnection(config);
let str;
rl.question("What do you want search for? (min); ", async (min) => {
rl.question("What do you want search for? (max); ", async (max) => {
str = await searchBetween(db, min, max);
console.info(str);
rl.close();
db.end();
});
});
})();
// Ge en rapport med larare details och formaterad text.
async function searchBetween(db, min, max) {
let sql;
let res;
let str;
let minimum = `${min}`;
let maximum = `${max}`;
console.info(`Searching for: ${minimum} - ${maximum}`);
sql = `
SELECT
akronym,
fornamn,
efternamn,
avdelning,
lon,
kompetens
FROM larare
WHERE
(kompetens BETWEEN ? AND ?)
OR
lon BETWEEN ? AND ?
ORDER BY akronym;
`;
res = await db.query(sql, [minimum, maximum, minimum, maximum]);
str = teacherAsTable(res);
return str;
}
// HERE SHOULD BE teacherAsTable
let res;
res = utils.teacherAsTable();
console.log(res);
答案 0 :(得分:0)
尝试在Between1.js中执行此操作:
module.exports = {teacherAsTable};