节点javascript需要js文件吗



我只想将js文件的内容加载到我的变量中!但它还给我一个物体?我怎样才能做到这一点?

server.js

const file = require("./server/file.js");
ctx.body = `${file}`; // Should return "(function () { console.log("ok");})";

//file.js

(function () {
console.log("ok");
});

使用文件读取器,查看此文档NodeJs网站

var fs = require('fs');
fs.readFile('./server/file.js', 'utf8', function(err, data) {
if (err) throw err;

const fileContent = data;
console.log(fileContent);
});

任何CommonJS模块都会导出module.exports的值,默认为空对象(即您所看到的(。

您的模块没有显式导出任何内容。

它有一个函数表达式,你什么都不做(你不调用它,不把它分配到任何地方,也不把它传递到任何地方:这完全没有意义(。

如果要导出函数,则需要显式导出。

function myFunction() {
console.log("ok");
}
module.exports = myFunction;

最新更新