[英]Node.js module.exports vs filesystem
In node when I require a file, it's normally and by default an object coming from node's module exports. 在我需要文件的节点中,它通常是默认情况下来自节点模块导出的对象。
So I am wondering other than the synchronously nature of module.exports
and the asynchronously nature of fs
what would be the other differences between retrieving a JSON file via module.exports vs the filesystem library, good/bad | 所以我想知道除了
module.exports
的同步特性和fs
的异步性质之外,通过module.exports与文件系统库检索JSON文件之间的其他区别是什么,好/坏 pros/cons. 优点缺点。 Thanks!
谢谢!
file_1.js file_1.js
module.exports = [{A-JSON}];
file_2.js file_2.js
require json from ('./file_1');
console.log(json);
file_1.js file_1.js
[{A-JSON}]
file_2.js file_2.js
fs = require('fs');
fs.readFile('./file_1', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
First you should know that require
can also be used to load json files - as documented here . 首先,您应该知道
require
也可以用于加载json文件 - 如此处所述 。
So for your second scenario, just rename to file_1.json
and you can use require as well. 因此,对于第二种情况,只需重命名为
file_1.json
,您也可以使用require。
In that case, if you use fs
you will need to JSON.parse
your file manually, while require
will automatically do it for you. 在这种情况下,如果你使用
fs
你需要手动JSON.parse
你的文件,而require
会自动为你做。
Another difference is that the require
system uses a cache, so that if you want to use the same object in another file, it will not read again from the filesystem 另一个区别是
require
系统使用缓存,因此如果你想在另一个文件中使用同一个对象,它将无法再从文件系统中读取
I think it's better to follow the standard and use require
whenever it's possible. 我认为最好遵循标准并尽可能使用
require
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.