How to exit javascript / node.js inside HTML - javascript

I have json file ( I create this json file using node.js) that I read in HTML using json2html library and if the json file is present / readble then it will be uploaded in our server.
I have json2html code that reads json file and prints HTML page based on content of json file. If json file is unreadable or not present, then I want node.js / javascript to stop or exit the process so nothing gets uploaded to server. How shall I stop / exit the code from processing further if json file is not available.
I do have process.exit() in my HTML file where I read json file . It does not exit gracefully. When I do inspect elements, it errors Uncaught (in promise) ReferenceError: process is not defined. I do have npm i process even though process is global. I still explicitly define const process = require('process'); in my index.js file. Still I get error while opening my html file in browser. How to get past this error. Please refer below for my code from my html file
let responseContent = fetch('studentRecords.json')
.then(function(response) {
return response.json();
})
.catch(function(err) {
process.exit(1);
});

The problem here is that you are trying to reference process which is a node global variable from the browser in your HTML file. Because of this, it won't exist.
Based on what you've mentioned, you can leave the code block as is and instead of running process.exit(1) you could try logging out an error or wrapping it in a callback function and returning an error instead? That way it won't try to process the fetch response and it will have the option to continue in the way you see fit.

Related

how to read text file in folder with javascript

I have a folder structure like this
index.html
file.txt
in the index.html I have a script that wants to read the file.txt and assign it to a variable, say x.
async function loadFile(file) {
let text = await file.text();
console.log(text);
return text
}
var x = loadFile("file.txt")
but this returns an error
main.js:35
Uncaught (in promise) TypeError: file.text is not a function
at loadFile (main.js:35:27)
at main.js:39:13
what to do? I just want to assign file.txt content to a variable.
JavaScript in browser doesn't give you direct access to file system.
What you did is just pass a string to your function and call text() on it. Sadly it doesn't work like that.
Here are two workarounds I know of:
1. fetch api
If you have an http server serving your files then you make a request using fetch() to obtain its content in JS. Read the docs here :
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Note that it won't work on pages loaded with file:// URI scheme. You need http(s). If you have python installed run python -m http.server 8000 in directory containing files to be served.
2. FileReader
If the file is to be selected by user as input to a form then you can use FileReader
Have a look these links:
webdev has great explaination for this
https://web.dev/read-files/
also see the docs
https://developer.mozilla.org/en-US/docs/Web/API/FileReader

How to read file input from 'Code by Zapier' (Javascript)

I'm fetching files from a Zapier trigger (with a BrickFTP app).
I'm then invoking the code app (in Javascript) to process the file (parse CSV), using the 'File' attribute of the BrickFTP app as input variable to the code step but cannot successfully read the file content.
The Code step is pretty trivial:
console.log(`Got file content: ${fileContent}`);
output = {
file: fileContent,
}
When I test the code step, I'm getting this error:
Bargle. We hit an error creating a run javascript. :-( Error:
[LazyFile] (3587 bytes) https://zapier.com/engine/hydrate/691575/.eJwtkFFrwjAUhf_KuM9i1mq3WRhjohSERjaqw76ULL2apG3aJVFR6X9fKr4evnu-w72B1NYxzbGQJcRh9BZFs2A6gr3Euiw0axBiKPFU7GWNMAIukFdFhReIX2ZB9Br5qNUOtSvcpRtg6qnqzMzBQnyDo6l9JpzrbEwI67rxr5G82rtuzNvGB5IYtI6cAjIYLCFSE-eTMbenD8adbPW7wVIa5M43PySPNQ065i39CAz-Hf3VoBTISjR3--fRidbIKxtq_NmcWcmf0uthQputyrPlOVfLyU5tAqpok_5spnSxklTNZZ7x53Um1DrZql0mGprsLrlKPT-vafItUrUSNPyaeFakYRqtF90U-vsi0fpPQrLMoO_7f_ftdsQ:1do4Qj:pEkOihXff9eAzu8eLyTpN378vgI/ is not JSON serializable
Screenshots:
The test data
Test results
I had the same problem, and that was because the field type I was assigning was text rather than file. First, you have to use CLI version of Zapier, and then if a field is supposed to accept files, it must be of type 'file'.
In this way, the url of the file is being returned and can be downloaded.

MongoDB run javaScript file from console and output

I am trying to create some mongoDB script (files upload to collections, find, create new collections etc). Though get confused. When I run in console:
> use importCSV
> db.people.find().pretty()
I get documents from collection on my screen, though when I run load command
> load('e:/work/parse/script.js')
i get output
true
Here javaScript file list
db = db.getSiblingDB('importCSV');
db.people.find().pretty();
I do it for debug purpose, so I create javaScript line by line to get what I want, and I need to see step by step some commands output. If I put to javaScript file command like this
print('Print from javaScript file');
it prints to console without any problems.
Why I get "true" when run from file instead of console output, and how to get list of documents printed when run from javaScript file?
Thanks
This is an expected behaviour. You need to iterate through the cursor and print each document explicitly using a .forEach loop because you are not using the interactive shell.
db = db.getSiblingDB('importCSV');
db.people.find().forEach(function(doc) {
printjson(doc);
}

How to use PowerShell output in JavaScript

I would like my JavaScript to use the PowerShell output, which is in JSON format, so I can draw a Google data table.
I have tried using window.clipboardData.getData('Text') but it doesn't seem like the answer I'm looking for and for some reason setTimeout() isn't working anymore. I have also tried event.dataTransfer.getData('Text') but I received an error
SCRIPT5007: Unable to get property 'getData' of undefined or null reference.
I kind of don't like having to copy to the clipboard because PowerShell does not take the same amount of time to finish executing every time. Additionally, the Google portion of the code constantly responds with error Invalid JSON string even though when I manually pasted the code, the data table loaded perfectly. I'm running on IE11.
You can install a HTTP server (like Apache or Lighttpd) on your computer and dump your JSON output in a .json file in the HTTP server directory.
Then you can make an ajax HTTP request to retrieved the file everytime you need it.

File Exists But Receiving ENOENT Error

Here is a gist: https://gist.github.com/973e70bde8e6a530c489
I have two scenarios. One works and one fails even though the code is exactly the same.
Take a CSV file already on the box and parse it. Works perfectly. No issues.
Take a CSV file that was just created and attempt to parse it and I receive:
ENOENT, no such file or directory '/Users/Home/dev/csv/TwFrI5vhdownload.csv
Same CSV file format and all that. Wouldn't matter anyway because the created file won't even open. It fails with the error above even though the file does exist. If I restart Node and attempt to grab that file, then it works perfectly. If I run fs.stat on the newly created file it fails.
I've tried timeouts, external callbacks, etc.. but with the dynamically created file it always fails.
What am I missing here? Is the file locked and I don't know it?
Thanks!
System:
OSX Lion
Node v0.6.7
Are you sure the file is actually created when you try to parse it?
I took a look on the gist and I guess you are downloading the file from somewhere and then parsing it. Without the whole code I can only guess, but I think that you started the download, but you haven't received a clear indication it is there and ready to be parsed.

Categories

Resources