readFileSync is not a function - javascript

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("\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:
Uncaught TypeError: fs.readFileSync is not a function
I have tried many fixes and cannot seem to figure this one out.

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("\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):
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.

This error can arise if you write
const fs = import('fs');
in a Node module
but should write
import fs from 'fs';

Related

Using javascript interpreter 'otto', How to read a file in client side

I'm having difficulties.
I am implementing logic to read the file, encodes it, and send it to the server.
Currently, the library used as javascript interpreter is using 'otto'.
I imported 'fs'(I know it is Built-in module) like
var fs = require("fs");
fs.readFileSync('./test.txt', 'utf8');
but occurred error Module not found: Error: Can't resolve 'fs'
So I inserted node: { fs: "empty" } in webpack.config.js file.
Then compile error is not occurred. But when I called a function that contains fs.readFileSync using cli, occurred error.
TypeError: 'readFileSync' is not a function
First question:
I know that 'otto' is just javascript interpreter. For this reason, when I imported 'fs', is there a failure to find the module?
Second question:
If not, How can I read a file from the clientside and send it to the server?
Last question: Using 'otto', It is impossible??
This is my spec.
macOS High Sierra, Webpack 4.9.1, Node.js 8.11.1.
How to read a file in client side
Since you mention Webpack, I'm assuming the "client side" here is a browser. To read a file from a browser, you use the File API. Note that your code cannot specify what file to read; the user does that, either by picking a file in an input type="file" element, or dragging a file into a drop area. In both cases, you'll get a File object, which you can read using the File API.
You cannot use the fs Node.js module in a browser.

Why is require module in JavaScript not able to import the fs library?

The javascript code is as follows:
const fs = require('fs');
function init() {
alert("Done!");
}
init();
While executing the Javascript code, I am not able to get the alert Done! on my webpage. On further analysis I came to a conclusion that it is most probably because the require statement is not working (there was an alert when I commented the require statement). Why is it so?
require is not available in the browser but is used in NodeJS. If you want to use it in your browser, you'll need a building tool like Browserify or Webpack.
By the way, the File System package is available in NodeJS only.

Require is not working for node-opcua

I want to load a local version of node-opcua with 'require' inside a HTML file, but it does not really work. The code snippet is the following:
<script type="text/javascript" src="path_to_require.js"></script>
<script>
var opcua = require(["path_to_node-opcua"]); <!-- Yes, the path is correct >
var client = new opcua.OPCUAClient();
...
When I execute the script I get the following error in the console:
Uncaught TypeError: opcua.OPCUAClient is not a constructor
Hence, var opcua is loaded correctly, but OPCUACluent is not, although the class is declared in a file that is present in the node-opcua folder called opcua_client.js under node-opcua\lib\client\
Sources:
The 'require' script from http://requirejs.org/docs/download.html#requirejs.
The node-opcua folder with the console command
npm install node-opcua.
node-opcua is not intended to run inside a browser as it relies on nodejs specific features such as filesystem access, crypto and so on.
You need to use browserify if you want to use that module in client. You will also need to look at how to use browserify with file system access (it can be done if paths are known ahead of time).

Node JS fs module inside browser

I have a scenario where I want to export data to CSV from the client-side. I will have a textbox/area or whatever where the user can input data and then ideally with one click, a local CSV file will be updated with that data.
This is easily achievable with NodeJS with server interaction, and its core modules (specifically fs module), but apparently not so much from a browser.
I found out that certain node modules (for example underscore), support RequireJS's method of making a particular module work in the browser. So for underscore I did this:
methods.js
define(['underscore'],function(_) {
var Methods = {
doSomething: function() {
var x = _.size({one: 1, two: 2, three: 3, xuz: 3});
alert(x);
}
};
return Methods;
});
common.js
requirejs.config({
baseURL: 'node_modules',
paths: {
underscore: 'underscore/underscore',
}
});
require(['methods'], function(y){
y.doSomething();
});
index.html
<script data-main="common" src="require.js"></script>
<script>
require(['common'], function() {
require(['methods.js']);
});
</script>
The above works fine and will show an alert: 4.
But when I try the same with the fs module it won't work. It will show this error:
Module name "util" has not been loaded yet for context: _. Use require([])
As far as I can understand, this is because fs requires several other modules, one of them being util.
So I proceeded to add all these modules to the RequireJS config. But still no luck, so I specifically tested util module by itself as this doesn't seem to require other modules to work.
And now I am stuck on this error: Uncaught ReferenceError: exports is not defined
I tried modularizing this util module by encapsulating the whole module source code in this:
define([], function() {})
But it didn't work either... I've also tried copying underscore's model but still no luck.
So I was wondering if anyone managed to use util & fs modules (or any other core NodeJS modules) within the browser with libraries such as RequireJS or Browserify.
That's right, exports is node-specific JS (used to make part of your module available outside the module) and isn't supported by web-browsers. Even though NodeJS is technically JS, there are client specific properties (like the window property for browsers, and exports for NodeJS apps) that can't be interchanged.
That said, here's a client side JS answer to the CSV problem.
Your best bet (and probably only one) is to use HTML5 FileSystem API. I am not aware of any other browser feature that would allow to work with files on client computer except maybe Flash and similar solution.
I am bit confused by your browserify tag since you are not obviously using Browserify. That would fix your issue with "exports is not defined".

Access node.js File System module in Meteor

I'm creating a web app that will edit some config files stored on a user's HD, and decided to give Meteor a shot.
I'd like to use Node.js's File System module to handle to I/O of the config files, but I haven't been able to figure out how to include the module. After some searching, I found the following code here on StackOverlow, which is supposed to allow me to require the module:
var require = __meteor_bootstrap__.require;
var fs = require('fs');
However, even with this placed inside of the if(server) portion of my code, my application is still throwing an error and telling me that 'fs' is undefined.
Has anyone else encountered this issue?
From 0.6.0 you need to use Npm.require
var fs = Npm.require('fs');

Categories

Resources