Javascript readFileSync 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37418513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
readFileSync is not a function
提问by L1ghtk3ira
I am relatively new to Node.js and have been looking around but cannot find a solution. I did check the require javascript file and it does not seem to have a method for "readFileSync". Perhaps I don't have a proper require file? I had a hard time finding this file, everywhere talked about it but most people did not post where to get it.
我对 Node.js 比较陌生,一直在环顾四周,但找不到解决方案。我确实检查了 require javascript 文件,它似乎没有“readFileSync”的方法。也许我没有合适的需求文件?我很难找到这个文件,到处都在谈论它,但大多数人没有发布从哪里获取它。
I installed Node.js and have the require.js file. My current code is like this:
我安装了 Node.js 并有 require.js 文件。我目前的代码是这样的:
fs = require(['require'], function (foo) {
//foo is now loaded.
});
console.log("\n *STARTING* \n");
// Get content from file
var contents = fs.readFileSync("sliderImages", 'utf8');
I had a bit at first getting require to work however it seems to load the require JavaScript file. I have been following guides and I am not sure why I get this error:
起初我有一点需要工作,但它似乎加载了 require JavaScript 文件。我一直在遵循指南,但我不确定为什么会出现此错误:
Uncaught TypeError: fs.readFileSync is not a function
未捕获的类型错误:fs.readFileSync 不是函数
I have tried many fixes and cannot seem to figure this one out.
我已经尝试了很多修复,但似乎无法解决这个问题。
采纳答案by Mike Cluck
Node.js does not use Require.js. Require.js was built so that you could have asynchronous module loading on the client-side (in your browser).
Node.js 不使用Require.js。Require.js 的构建是为了让您可以在客户端(在您的浏览器中)进行异步模块加载。
Node.js uses CommonJSstyle modules. Your code using CommonJS would look like this:
Node.js 使用CommonJS风格的模块。您使用 CommonJS 的代码如下所示:
var fs = require('fs');
console.log("\n *STARTING* \n");
var contents = fs.readFileSync("sliderImages", "utf8");
If we assume you saved this in a file called main.js
you would then enter this command in your console (make sure you are in the same directory as the file):
如果我们假设您将其保存在一个名为main.js
您的文件中,那么您将在控制台中输入此命令(确保您与该文件位于同一目录中):
node main.js
This code will notrun in the browser. Node.js runs on the server. If you want to load a JSON file on the browser side then you'll need to load it using AJAX. There are numerous resourcesavailable to show you how to do this. Be aware that you must either run your page from a server or have a special flag enabled to load in files from the file system.
此代码不会在浏览器中运行。Node.js 在服务器上运行。如果要在浏览器端加载 JSON 文件,则需要使用 AJAX 加载它。有许多资源可以向您展示如何执行此操作。请注意,您必须从服务器运行页面或启用特殊标志以从文件系统加载文件。