readFileSync不是一个函数 [英] readFileSync is not a function

查看:918
本文介绍了readFileSync不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Node.js比较陌生,一直在环顾四周但找不到解决方案。我确实检查了需要的javascript文件,它似乎没有readFileSync的方法。也许我没有合适的require文件?我很难找到这个文件,到处都在谈论它,但大多数人都没有发布到哪里去。

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.js文件。我目前的代码是这样的:

I installed Node.js and have the require.js file. My current code is like this:

fs = require(['require'], function (foo) {
//foo is now loaded.
});
console.log("\n *STARTING* \n");
// Get content from file
var contents = fs.readFileSync("sliderImages", 'utf8');

我有点起初要求工作,但似乎加载了需要的JavaScript文件。我一直在关注指南,我不知道为什么会出现这个错误:

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:


未捕获的TypeError:fs.​​readFileSync不是函数

Uncaught TypeError: fs.readFileSync is not a function

我尝试了很多修复工具,似乎无法解决这个问题。

I have tried many fixes and cannot seem to figure this one out.

推荐答案

Node.js不使用 Require.js 。构建了Require.js,以便您可以在客户端(在浏览器中)加载异步模块。

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使用 CommonJS 样式模块。使用CommonJS的代码如下所示:

Node.js uses CommonJS style modules. Your code using CommonJS would look like this:

var fs = require('fs');
console.log("\n *STARTING* \n");
var contents = fs.readFileSync("sliderImages", "utf8");

如果我们假设您将此保存在名为 main.js的文件中然后您将在控制台中输入此命令(确保您与文件位于同一目录中):

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):

node main.js

此代码不会在浏览器中运行。 Node.js在服务器上运行。如果要在浏览器端加载JSON文件,则需要使用AJAX加载它。 资源众多可以告诉你如何做到这一点。请注意,您必须从服务器运行页面或启用特殊标志才能从文件系统加载文件。

This code will not run 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 resources available 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.

这篇关于readFileSync不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆