ReferenceError: File is not defined - express - javascript

I`m trying to convert some base64 string to a image file and pass it to firebase via express.
Everything works fine on front end, except this part:
const convertBase64ToFile = (base64String, fileName) => {
let arr = base64String.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let uint8Array = new Uint8Array(n);
while (n--) {
uint8Array[n] = bstr.charCodeAt(n);
}
const file = new File([uint8Array], fileName, { type: mime }); /// getting Error in this line
return file
}
Which library i have to import?
Error:
const file = new File([uint8Array], fileName, { type: mime }); /// getting Error in this line
^
ReferenceError: File is not defined
at convertBase64ToFile (C:\Users\rahto\devel\new\maissaudeapi\api\firestore\write.js:19:16)
at conversor (C:\Users\rahto\devel\new\maissaudeapi\api\firestore\write.js:33:16)
at C:\Users\rahto\devel\new\maissaudeapi\mainServer.js:31:21
at Layer.handle [as handle_request] (C:\Users\rahto\devel\new\maissaudeapi\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\rahto\devel\new\maissaudeapi\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\rahto\devel\new\maissaudeapi\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\rahto\devel\new\maissaudeapi\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\rahto\devel\new\maissaudeapi\node_modules\express\lib\router\index.js:284:15
at Function.process_params (C:\Users\rahto\devel\new\maissaudeapi\node_modules\express\lib\router\index.js:346:12)
at next (C:\Users\rahto\devel\new\maissaudeapi\node_modules\express\lib\router\index.js:280:10)
Node.js v18.6.0
[nodemon] app crashed - waiting for file changes before starting...
Then, i changed to this:
const convertBase64ToFile = (base64String, fileName) => {
let arr = base64String.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let uint8Array = new Uint8Array(n);
while (n--) {
uint8Array[n] = bstr.charCodeAt(n);
}
const file = fs.writeFileSync(fileName, uint8Array)
let fiz = fs.readFileSync(fileName, file);
// const file = new File([uint8Array], fileName, { type: mime });
return fiz
}
And got this error:
C:\Users\rahto\devel\new\maissaudeapi\node_modules\#firebase\storage\dist\index.node.cjs.js:3036
const newPath = child(ref._location.path, childPath);
^
TypeError: Cannot read properties of undefined (reading 'path')

It seems you are using node runtime. You can use fs module to access file system.
fs.writeFile( file, data, options, callback )
Parameters: This method accept four parameters as mentioned above and described below:
file: It is a string, Buffer, URL or file description integer that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similar to fs.write() method.
data: It is a string, Buffer, TypedArray or DataView that will be written to the file.
options: It is an string or object that can be used to specify optional parameters that will affect the output. It has three optional parameter:
encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’.
mode: It is an integer value that specifies the file mode. The default value is 0o666.
flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’.
callback: It is the function that would be called when the method is executed.
err: It is an error that would be thrown if the operation fails.
Usage:
var fs = require('fs');
fs.writeFile('file.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
Also check more here and here for usage.
And also check here for documentation.

Related

TypeError: Expected the input argument to be of type Uint8Array or Buffer or ArrayBuffer, got object

So I have made a Meme Gallery app.
Here is the link:https://meme-gallery-web-app.netlify.app/
You can upload an image via link. First of all I was trying to check if the submitted URL had the jpg/png extension, so I can work with it(whether to upload it or not).
That's why I tried to implement Image-type package. But it gives me the mentioned error.
Here is the code where I implemented.
const https = require("https");
const imageType = require("image-type");
const imageModel = require("../models/models.js");
var date = new Date();
var currentDate = date.toLocaleDateString();
const submitLink = async (req, res) => {
const { url } = req.body;
https.get(url, (response) => {
response.on("readable", () => {
const chunk = response.read(imageType.minimumBytes);
response.destroy();
console.log(imageType(chunk));
});
});
};
After submitting the link I got the following error:
TypeError: Expected the input argument to be of type Uint8Array or Buffer or ArrayBuffer, got object
So I checked and found out that the variable chunk is an object rather than an Uint8Array or Buffer. Why is that? And how to workaround it?
I think you should read the chunks, concat them and pass the resulting buffer to the imageType library:
https.get(url, response => {
const chunks = [];
response.on("data", (chunk) => {
chunks.push(chunk);
})
response.on("end", () => {
const resultBuffer = Buffer.concat(chunks);
console.log("image type is", imageType(resultBuffer ));
})
});

The "path" argument must be of type string. Received type undefined (fs module nodejs)

I am trying to check if a file exists using fs module in nodejs. Please refer to the following code:
var path = require('path');
let customXmlPath = (process.platform == 'darwin' ? path.join(__dirname, '../../MacOS/service/custom.xml') : path.join(__dirname, '../../service/custom.xml'));
if (isDevelopment) {
customXmlPath = (process.platform == 'darwin' ? path.join(__dirname, '../../../build/bin/darwin/release/custom.xml') : path.join(__dirname, '../../../build/bin/msvc/release/custom.xml'));
}
console.log(customXmlPath);
const fs = require('fs');
let productDisplayName = "xxxxxx";
try {
fs.accessSync(customXmlPath, fs.F_OK);
let file = fs.readFileSync(customXmlPath, "utf8");
var xmlr = require('../../../shared/electronUIshared/xmlreader.js').XMLReader;
var datastore = xmlr.parse('config', file);
if(datastore.getTotalCount() > 0)
{
productDisplayName = datastore.getRecordAt(0).get('productname');
}
}
catch(err) {
console.log("custom.xml not found or is corrupted. Using display name as xxxxxx")
}
In windows it works fine but in mac it throws an error in fs.acessSync: The "path" argument must be of type string. Received type undefined.
path.join returns correct path
Output:
/Users/nikhell/Documents/Codelathe/Workspace/cl-fc-client/build/bin/darwin/release/custom.xml
App threw an error during load
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
at validateString (internal/validators.js:105:11)
at Object.join (path.js:1037:7)
at eval (webpack:///./src/background.ts?:70:21)
at Module../src/background.ts (/Users/nikhell/Documents/Codelathe/Workspace/cl-fc-client/clouddrive2service/ui/dist_electron/index.js:6094:1)
at __webpack_require__ (/Users/nikhell/Documents/Codelathe/Workspace/cl-fc-client/clouddrive2service/ui/dist_electron/index.js:20:30)
at eval (webpack:///multi_./src/background.ts?:1:18)
at Object.0 (/Users/nikhell/Documents/Codelathe/Workspace/cl-fc-client/clouddrive2service/ui/dist_electron/index.js:6201:1)
at __webpack_require__ (/Users/nikhell/Documents/Codelathe/Workspace/cl-fc-client/clouddrive2service/ui/dist_electron/index.js:20:30)
at /Users/nikhell/Documents/Codelathe/Workspace/cl-fc-client/clouddrive2service/ui/dist_electron/index.js:84:18
at Object.<anonymous> (/Users/nikhell/Documents/Codelathe/Workspace/cl-fc-client/clouddrive2service/ui/dist_electron/index.js:87:10)
If i remove the file extension it does not throw the error but it is not able to find the file. Why is the file extension creating issues in mac?

How to convert Base64 into HTML using node js

Here i tried converting the base64 to html using the Mammoth npm, but it is throwing an error: -
throw new Error(“Can’t find end of central directory : is this a zip file ? ” +
Error: Can’t find end of central directory : is this a zip file ? If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html
at ZipEntries.readEndOfCentral (/Users/Desktop/mommoth/node_modules/jszip/lib/zipEntries.js:149:23)
at ZipEntries.load (/Users/Desktop/mommoth/node_modules/jszip/lib/zipEntries.js:215:14)
at new ZipEntries (/Users/Desktop/mommoth/node_modules/jszip/lib/zipEntries.js:21:14)
at JSZip.module.exports [as load] (/Users/Desktop/mommoth/node_modules/jszip/lib/load.js:11:18)
at new JSZip (/Users/Desktop/mommoth/node_modules/jszip/lib/index.js:39:14)
at Object.openArrayBuffer (/Users/Desktop/mommoth/node_modules/mammoth/lib/zipfile.js:10:19)
at Object.openZip (/Users/Desktop/mommoth/node_modules/mammoth/lib/unzip.js:16:41)
at convert (/Users/Desktop/mommoth/node_modules/mammoth/lib/index.js:34:18)
at Object.convertToHtml (/Users/Desktop/mommoth/node_modules/mammoth/lib/index.js:22:12)
at /Users/Desktop/mommoth/server.js:49:10
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)
let base64String = 'data:text;base64,TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=';
let base64Path = base64String.split(';base64,').pop();
let buff = new Buffer(base64Path, 'Base64');
console.log(buff);
mammoth.convertToHtml({ buffer : buff })
.then(function(error,result){
if(error){console.error(error)}
else{
console.log('convert');
console.log(result);
}
})
.done();
});
What is your node version?
new Buffer(base64Path, 'base64');
This method is for Node.js v5.11.1 and below, if your Node.js version is v6.0.0 or above, you should convert in this way
let buff = Buffer.from(base64Path, 'base64');

Node js - Why lstatSync(Path) returns undefined ? - synchronously check

I'm new to Node.js , and i'm trying to create a simple server
the problem is:
TypeError: Cannot read property 'isFile' of undefined
what i did so far :
I tried a simple debugging process to find out where the problem exactly
and the problem as i expect in the returning value of lstatSync()
lstatSync() returns undefined all the time , which is a cause the problem in isFile()
Notes :-
I checked in a sample code below the path that i pass to lstatSync() by logging the value in the console and it was as expected
Also after some research i tried to use fs.exists() but i found out that it's deprecated !
Finally the Docs doesn't provide much about the function
Sample Code :
var http = require("http"); // creating server
var path = require("path"); // finding the actual path for directories / files
var url = require("url"); // parse url
var fs = require('fs'); // file system core , dealing with files operations
// Array of mime types ..
var mimeTypes = {
'html' : 'text/html',
'css' : 'text/css',
'js' : 'text/javascript',
'jpg' : 'image/jpg',
'png' : 'image/png',
'jpeg' : 'image/jpeg'
}
// creating server ...
http.createServer(function(req , res){
var uri = url.parse(req.url).pathname // parse url , exctract the path after the host name 'incuding /'
var fileName = path.join(process.cwd(),unescape(uri)); // returing current directory path , unescape the url path in case it contains special char.
console.log("data is loading"+uri);
console.log("File name : "+fileName);
var stats;
try {
stats = fs.lstatSync(fileName) // Returns an instance of fs.Stats.
console.log(stats);
} catch (e) {
console.log(stats);
// if the file not exists [NOT FOUND]
res.writeHead(404,{'Context-Type':'text/plain'});
res.write('Error 404 , page not Found \n');
res.end();
}
// file actual path is a file / directory
// file it's a file
if(stats.isFile()){
var mimeType = mimeTypes[path.extname(fileName).split('.').reverse()[0]]; // file name without extension
res.writeHead(200,{'Content-Type':mimeType});
var readStream = fs.createReadStream(fileName);
readStream.pipe(res);
}else if(stats.isDirectory()){
res.writeHead(302,{
'Location' : 'index.html'
});
res.end();
}else{
res.writeHead(500,{'Content-Type':'text/plain'});
res.write('500 Internal Error \n');
res.end();
}
}).listen(8888);
Calling res.end() doesn't magically stop the rest of the function to run. In the catch handler, you should return from the function explicitly:
try {
stats = fs.lstatSync(fileName) // Returns an instance of fs.Stats.
console.log(stats);
} catch (e) {
console.log(stats);
// if the file not exists [NOT FOUND]
res.writeHead(404,{'Context-Type':'text/plain'});
res.write('Error 404 , page not Found \n');
return res.end();
}
Note that the HTTP server doesn't do anything with the return value of the handler, so return res.end() is just a shortcut for res.end(); return;.

How read stream .pipe(myfunction())

How read stream .pipe(myfunction())?
I try , but give errors. How read stream of gulp.src('./userdata.json') and .pipe()? I not know how is it make.
gulpfile.js
var upmodul = require("modul-json");
//......
return gulp.src('./userdata.json')
.pipe(upmodul());
......//
node_modules / modul-json / index.js
'use strict';
var Stream = require('stream');
var loger = function () {
var readable = new Stream.Readable({
read: function (n) {
this.push("ll");
}
});
}
module.exports = loger;
Error
[00:19:39] TypeError: Cannot read property 'on' of undefined
at DestroyableTransform.Readable.pipe (E:\Developers\WebDeveloper\OpenServer
-WebProg\domains\progectapi2\node_modules\vinyl-fs\node_modules\readable-stream\
lib\_stream_readable.js:516:7)
at Gulp.<anonymous> (E:\Developers\WebDeveloper\OpenServer-WebProg\domains\p
rogectapi2\gulpfile.js:159:9)
at module.exports (E:\Developers\WebDeveloper\OpenServer-WebProg\domains\pro
gectapi2\node_modules\orchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask (E:\Developers\WebDeveloper\OpenServer-WebProg
\domains\progectapi2\node_modules\orchestrator\index.js:273:3)
at Gulp.Orchestrator._runStep (E:\Developers\WebDeveloper\OpenServer-WebProg
\domains\progectapi2\node_modules\orchestrator\index.js:214:10)
at Gulp.Orchestrator.start (E:\Developers\WebDeveloper\OpenServer-WebProg\do
mains\progectapi2\node_modules\orchestrator\index.js:134:8)
at C:\Users\Tiki
\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:20
at nextTickCallbackWith0Args (node.js:433:9)
at process._tickCallback (node.js:362:13)
at Function.Module.runMain (module.js:432:11)
The gulp documentation has some information on building a plugin that might be useful to you. Just a sample from that page talks about transforming streams.
All gulp plugins essentially boil down to this:
var Transform = require('stream').Transform;
module.exports = function() {
// Monkey patch Transform or create your own subclass,
// implementing `_transform()` and optionally `_flush()`
var transformStream = new Transform({objectMode: true});
/**
* #param {Buffer|string} file
* #param {string=} encoding - ignored if file contains a Buffer
* #param {function(Error, object)} callback - Call this function (optionally with an
* error argument and data) when you are done processing the supplied chunk.
*/
transformStream._transform = function(file, encoding, callback) {
var error = null,
output = doSomethingWithTheFile(file);
callback(error, output);
});
return transformStream;
};

Categories