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

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.

Related

Uncaught TypeError: Failed to resolve module specifier "fs". Relative references must start with either "/", "./", or "../"

When I try to import the fs module in my own module like import * as fs from 'fs' the following error in the browser console comes:
Uncaught TypeError: Failed to resolve module specifier "fs". Relative references must start with either "/", "./", or "../".
Using require or using a relative path to the module like ./node_modules/fs will not work, is there any other way of importing the fs module correctly?
You have two basic problems, both of which stem from the fact you are running this code in a browser and not in Node.js.
Passing something like 'fs' to import depends on Node.js style module resolution. Node.js will search the contents of the node_modules folder for matching modules. Browsers can't do that, they haven't got a file system to search; they only deal in URLs.
When dealing with modules in a browser you have to pass either:
A URL that includes an absolute path (like /fs or http://example.com/fs)
A URL that is an explicitly relative path (like ../fs or ./fs).
… just like the error message says.
(Typically you'll also need to put a .js on the end of the URL because your HTTP server is unlikely to do that for you).
You also need to use a module which will run in a browser in the first place.
fs is a Node.js built-in module. It does things which browsers do not allow JavaScript to do (like access the file system).
If you want to use the fs module then you can't use it directly from the browser. Instead, write a web service in Node.js (the Express.js module is useful here) and access it from the browser using Ajax (e.g. the fetch API). This will deal with the server's file system, not the browser's.
If you want to access files on the user's computer, then you'll need to use <input type="file"> and the FileReader API.

Json "require" converted to Module "require" when installing packages

So... Lets say you have this library you want to post to NPM.
You convert it to a module type and use:
import {createRequire} from "module";
const require = createRequire(import.meta.url);
To implement require onto it. As you may know require can be used to read JSONs. So you try to read a json. Everything works fine when you test it onto a local machine. When you try linking it tho and you try to call that function it throws:
Error: Cannot find module 'something.json'
Is this an on going npm issue and if so how can i avoid it? Is there another way to read JSONs other than reading them as a txt file (which isn't very practical)?

Why do I get the error "Response has unsupported MIME type" after bundling Wasm together, but not when serving with the webpack dev server?

I am trying to make a Rust WebAssembly project and have modified the rust-webpack-template as my starting point. The template is a webpack project with a JavaScript file that calls a single Wasm function and the Rust Wasm takes over from there.
I have modified the template because I would like to have my main logic in JavaScript and call the Rust Wasm through an API.
I have changed the webpack entry to bootstrap.js shown below.
// bootstrap.js
import("./index.js").catch(e =>
console.error("Error importing 'index.js':", e)
);
I added the file index.js and it calls the Rust Wasm functions
// index.js
import * as wasm from "../crate/pkg/rust_webpack";
const title = document.getElementById("msg");
title.innerText = wasm.get_msg();
The get_msg function from Rust looks like this:
#[wasm_bindgen]
pub fn get_msg() -> String {
"Hello from Rust WebAssembly!".to_owned()
}
When I run the project using webpack-dev-server -d, everything works fine.
However, when I build the project using webpack and try and host the generated files directly, nothing is displayed and the browser console displays the error:
Error importing 'index.js': TypeError: "Response has unsupported MIME type"
This error comes from the code in bootstrap.js but I'm not entirely sure what it means or how to fix this error.
Why do things work when serving with the webpack dev server but not after bundling everything together?
As Shepmaster helped me to figure out in the comments, the MIME type of the .wasm file is being set to application/octet-stream when the browser expects it to be application/wasm.
I am using a simple express server to host my files. Express can be configured to use the correct MIME type with a single line.
var express = require('express');
var app = express();
// Set the MIME type explicitly
express.static.mime.define({'application/wasm': ['wasm']});
app.use(express.static('./dist'));
app.listen(3000);
According to this issue, express will handle .wasm files correctly after version 4.17. It works correctly in webpack dev server because they implemented their own workaround while they wait for the fix in express.
I had a similar problem ("Response has unsupported MIME type") with Flask. The problem was that I didn't have a separate route to the .wasm file. For example:
#app.route('/path/to/file.wasm')
def wasm_file():
return send_file('/path/to/file.wasm', mimetype = 'application/wasm');
It is not the answer to this question, but it's a hint for other people who have a similar problem.
I also encountered this problem, leading me to change my .htaccess file (I'm using Apache to host my local server) to include the following:
AddType application/wasm wasm
If the error persists, and you are getting this error from using WebAssembly.instantiateStreaming, this related question may have an explanation and workaround: WebAssembly InstantiateStreaming Wrong MIME type

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("\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';

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