I've recently started to work on NodeJS, and in particular the knex module to query and insert into databases from the browser.
I've tested my code on my own computer, which worked. For the browser, however, I needed to use the module browserify to transform my code in the right manner (into a bundle.js file).
But, when I load the file in the browser, it gives me an error stating the following:
bundle.js:1 Uncaught Error: Cannot find module './dialects/mysql/index.js'
In the coding, the error gets thrown after this part:
var Dialect;
if (arguments.length === 0 || !config.client && !config.dialect) {
Dialect = makeClient(Client);
} else {
var clientName = config.client || config.dialect;
Dialect = makeClient(require("./dialects/" + (aliases[clientName] ||clientName) + "/index"));
}
After this, and error is thrown, while the file does actually exist in the path that is specified. furthermore, lines of code before this, like for example:
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
Do actually work fine, so I guess it cannot be that the function is searching in the wrong directory. I'm running out of new ideas on how to possibly fix this, so I'm hoping that someone knows a bit more about this.
Related
I am following the instruction given here to integrate antlr4 with ace editor and I have trouble at the step var antlr4 = require('antlr4/index');. The author mentions that here we should use require for nodejs. However, ACE has another require that may cause problems. Thus he loaded another script for nodejs require and load antlr4/index with require in that script.
I tried that one, too. But it always cannot find the script. From the console of my browser, I can see the path it loads the script is:
localhost:4200/./antlr4/index.js and it fails to load it.
I am using Angular 7, and the structure of my project is as follows:
Also, when loading some local javascript file using importScripts, I always fails by giving the local path, however, giving URL from CDN will always work. But importScripts should support local file importing.
Where should I make changes and what else methods should I try?
Here are some of my code:
var ace_require = require;
window.require = undefined;
var Honey = { 'requirePath': ['..'] };
//importScript{"require.js"}
//the script can't be imported through importSctipt so I pasted the
//whole script file under...(not shown here)
var antlr4_require = window.require; // antlr4_require:antlr using nodejs require;
window.require = require = ace_require; // require:ace using its own require
var antlr4, LPMLNLexer, LPMLNParser;
try {
window.require = antlr4_require;
antlr4 = antlr4_require('antlr4/index');
//the browser stuck here reporting error...
} finally {
window.require = ace_require;
}
I'm developing some webGL project in Unity that has to load some external images from a directory, it runs all fine in the editor, however when I build it, it throws a Directory Not Found exception in web console. I am putting the images in Assets/StreamingAssets folder, that will become StreamingAssets folder in the built project (at root, same as index.html). Images are located there, yet browser still complains about not being able to find that directory. (I'm opening it on my own computer, no running web server)
I guess I'm missing something very obvious, but it seems like I could use some help, I've just started learning unity a week ago, and I'm not that great with C# or JavaScript (I'm trying to get better...) Is this somehow related to some javascript security issues?
Could someone please point me in the right direction, how I should be reading images(no writing need to be done) in Unity WebGL?
string appPath = Application.dataPath;
string[] filePaths = Directory.GetFiles(appPath, "*.jpg");
According to unity3d.com in webGL builds everything except threading and reflection is supported, so IO should be working - or so I thought:S
I was working around a bit and now I'm trying to load a text file containing the paths of the images (separated by ';'):
TextAsset ta = Resources.Load<TextAsset>("texManifest");
string[] lines = ta.text.Split(';');
Then I convert all lines to proper path, and add them to a list:
string temp = Application.streamingAssetsPath + "/textures/" + s;
filePaths.Add(temp);
Debug.Log tells me it looks like this:
file://////Downloads/FurnitureDresser/build/StreamingAssets/textures/79.jpg
So that seems to be allright except for all those slashes (That looks a bit odd to me)
And finally create the texture:
WWW www = new WWW("file://" + filePaths[i]);
yield return www;
Texture2D new_texture = new Texture2D(120, 80);
www.LoadImageIntoTexture(new_texture);
And around this last part (unsure: webgl projects does not seem easily debuggable) it tells me: NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
Can someone please enlighten me what is happening? And most of all, what would be proper to solution to create a directory from where I can load images during runtime?
I realise this question is now a couple of years old, but, since this still appears to be commonly asked question, here is one solution (sorry, the code is C# but I am guessing the javascript implementation is similar). Basically you need to use UnityWebRequest and Coroutines to access a file from the StreamingAssets folder.
1) Create a new Loading scene (which does nothing but query the files; you could have it display some status text or a progress bar to let the user knows what is happening).
2) Add a script called Loader to the Main Camera in the Loading scene.
3) In the Loader script, add a variable to indicate whether the asset has been read successfully:
private bool isAssetRead;
4) In the Start() method of the Loading script:
void Start ()
{
// if webGL, this will be something like "http://..."
string assetPath = Application.streamingAssetsPath;
bool isWebGl = assetPath.Contains("://") ||
assetPath.Contains(":///");
try
{
if (isWebGl)
{
StartCoroutine(
SendRequest(
Path.Combine(
assetPath, "myAsset")));
}
else // desktop app
{
// do whatever you need is app is not WebGL
}
}
catch
{
// handle failure
}
}
5) In the Update() method of the Loading script:
void Update ()
{
// check to see if asset has been successfully read yet
if (isAssetRead)
{
// once asset is successfully read,
// load the next screen (e.g. main menu or gameplay)
SceneManager.LoadScene("NextScene");
}
// need to consider what happens if
// asset fails to be read for some reason
}
6) In the SendRequest() method of the Loading script:
private IEnumerator SendRequest(string url)
{
using (UnityWebRequest request = UnityWebRequest.Get(url))
{
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
// handle failure
}
else
{
try
{
// entire file is returned via downloadHandler
//string fileContents = request.downloadHandler.text;
// or
//byte[] fileContents = request.downloadHandler.data;
// do whatever you need to do with the file contents
if (loadAsset(fileContents))
isAssetRead = true;
}
catch (Exception x)
{
// handle failure
}
}
}
}
Put your image in the Resources folder and use Resources.Load to open the file and use it.
For example:
Texture2D texture = Resources.Load("images/Texture") as Texture2D;
if (texture != null)
{
GetComponent<Renderer>().material.mainTexture = texture;
}
The directory listing and file APIs are not available in webgl builds.
Basically no low level IO operations are supported.
I'm trying to migrate a node project to run in the browser. The project (nevermind the reason for the moment) writes to a temporary file, using temp with code similar to this:
var temp = require('temp');
var fs = require('fs');
temp.open('helloworld.txt', function (err, info) {
if (err) {
console.log('Failed to open a temp file:', err);
return;
}
console.log('temp: ', info.path);
fs.writeFile(info.path, 'Hello World!', function (err2) {
if (err2) {
console.log('Failed to write to a temp file:', err2);
return;
}
});
});
When running the browserified code I get the following error:
Uncaught TypeError: undefined is not a function
for the following line:
fs.open(filePath, RDWR_EXCL, 0600, function(err, fd) {
which is called by temp.open.
I'm very much aware you cannot write files using plain ol' javascript in the browser, but I was wondering if browserify have some replacement for that, especially since we're talking about a temp file.
I found browserify-fs, and tried:
browserify -r fs:browserify-fs my-example.js -o bfied.js
but I get the exact same error. I tried to replace require('fs') with require('browserify-fs') but this resulted in a similar error as well (I of course installed browserify-fs module..)
Any suggested solution would be appreciated :) If this type of migration is not possible, I'd also be glad to know..
Thanks!
I stumbled across this post as I think I was trying to do pretty much the exact same thing as you. I am not sure where you got to with this, but I found that when using browserify-fs, you cannot access files outside the sandboxed state of the browser.
So when trying...
var fs = require('broserify-fs);
fs.read('hello.txt', 'utf8' ....
I got the same error as you, but when doing this...
fs.mkdir('/home', function() {
fs.writeFile('/home/hello-world.txt', 'Hello world!\n', function() {
fs.readFile('/home/hello-world.txt', 'utf-8', function(err, data) {
console.log(data);
});
});
});
Everything worked fine (using just temporary files I think).
I am super new to this so I'm not sure what the best approach is. I imagine you either want to run a Node.js server locally and issue ajax commands to it to perform read/write operations, or investigate the HTML5 file system stuff - this looks like a good article - http://www.html5rocks.com/en/tutorials/file/dndfiles/
Hope that's some help (sorry you've had to wait 2 months for an answer ;) It was serendipitous I happened to stumble across your question and my heart sank when there were no answers)
Tom
This may be a bit of an odd question, I can't seem to search the right phrase to pull up any relevant answers.
We have an app that runs on clients machines and is minified. We generate source maps, but they are not exposed to production versions.
I have a window.onerror that I use a catch all for sloppy code that finds it's way in unbeknownst to me. Thankfully, this is almost never utilized. Recently, I've been getting an undefined error popping up occasionally so someone has found a way to do something not intended. Chrome does a nice job recording row and column number in the stack trace which we log to a logging server when onerror catches one of these buggers, but that's all I have to debug with and looking through a min file is less than appealing. And undefined is not a function is not very helpful either :)
Question: is there a tool out there - maybe in nodejs - that can take a min file, source map, and a stack trace string and produce relevant files, line numbers, and column numbers?
I realize that the browser does this for you at runtime, but in this case I don't have that luxury as I'm trying to figure out what the error actually is after the fact.
Found this: https://github.com/thlorenz/stack-mapper
I use uglify which seems to produce the correct mapping that this needs and it looks like it will work for the case I suggested above.
Edit
Actually, this one works a lot better and is much simpler to use https://github.com/mozilla/source-map/.
Example Usage:
var fs = require('fs');
var smc = require('source-map');
var stack = "TypeError: undefined is not a function\r\nat h/min/min.js?1404839824760:9:23048";
stack = stack.split(/\r\n/g);
var error = stack.shift(); // First line is the actual error
var errors = [];
var file = null;
stack.forEach(function(line){
var _trace = line.split('/').pop();
var trace = {};
trace.filename = _trace.split('?').shift();
_trace = _trace.split(':');
trace.line = parseInt(_trace[1], 10);
trace.column = parseInt(_trace[2], 10);
errors.push(trace);
if(!file)
file = trace.filename.split('.').shift();
trace.filename = __dirname + '/../min/' + trace.filename;
});
// This does not account for multiple files in stack trace right now
var map = fs.readFileSync(__dirname + '/../src/' + file + '.js.map');
map = JSON.parse(map);
var sm = new smc.SourceMapConsumer(map);
console.log(sm.originalPositionFor(errors[0]));
stacktrace.js looks to be another useful tool to achieve this.
Example from their website:
var error = new Error('BOOM!');
StackTrace.fromError(error).then(callback).catch(errback)
=> Promise(Array[StackFrame], Error);
There is a very popular project called source-map-support which does this easily.
Client-side JavaScript:
<script src="browser-source-map-support.js"></script>
<script>sourceMapSupport.install();</script>
NodeJS (programmatic)
require('source-map-support').install();
NodeJS (CLI)
node -r source-map-support/register compiled.js
I found https://github.com/thlorenz/stack-mapper easy to use to do this automatically. If you are looking to do this interactively, you can use stack-mapper in a web browser with a tool like this one: https://github.com/Jimbly/stackwalker - just load your .map file, paste the (minified) callstack or single error location and then you can click through the stack and see the original code on the right.
I'm trying to clone a Git repository that resides on my local drive into a new folder. So far, I've tried several modules, from which creationix/js-git seemed to be the most promising one.
The code to fetch I use is:
var source = '...',
target = '...';
var remoteRepository = git.remote('file://' + source),
localRepository = git.repo(target);
var options = {
onProgress: function (progress) {
console.log(progress);
}
};
localRepository.fetch(remoteRepository, options, function (err) {
if (err) { throw err; }
console.log('Done');
});
Unfortunately, this does not work, as js-git complains about an unknown URL format, which relates to the file:// protocol being used. The same error appears when I remove the file:// portion.
I also tried to change git.remote to git.repo (as it's not an actual remote), but then I get:
TypeError: Object #<Object> has no method 'discover'
So, apparently js-git does not support fetching from local repositories (or I was not able to find out how to do it).
Does anyone…
…either know how to solve this using js-git,
or can suggest a viable alternative?
Any help is appreciated :-)