Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

javascript - readFileSync is not a function

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.

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("
 *STARTING* 
");
// 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:

Uncaught TypeError: fs.readFileSync is not a function

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 uses CommonJS style modules. Your code using CommonJS would look like this:

var fs = require('fs');
console.log("
 *STARTING* 
");
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):

node main.js

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...