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

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?

Related

ReferenceError: File is not defined - express

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.

nodejs: Iterating through directory and capturing SHA256 value for each file

Goal: Iterate through all files in X directory and getting the SHA256 value for each file.
The code below seems to almost work; it captures the SHA256 value for ONE file but failed at the next iteration. I've done some googling but due to my limited understanding of node I'm not able to find the answer.
Speculation: after the first iteration; the code is not able to find the full path of anymore?
Error: [Error: ENOENT: no such file or directory, open 'example.txt'] {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'example.txt'
}
example.txt is the 2nd file in my directory, the code was able to get the value for the first file.
const fs = require('fs').promises
const hasha = require('hasha');
const path = require('path')
async function getAllFiles(pathToFiles){
let files = await fs.readdir(pathToFiles);
for (const file of files) {
const fullPath = path.join(pathToFiles, file)
const hash = await hasha.fromFile(file.toString(), {algorithm: 'sha256'});
console.log(hash);
}
}
getAllFiles('.').then(() => {
console.log("all done");
}).catch(err => {
console.log(err);
});
Figured out a solution: getting the absolute path for each file and passing that path to const hash worked.

Node.js (http server): How to improve this local network server for simple file sharing?

The following code creates a simple local server that serves specified file to other devices on the same network from 192.168.0.x:8080:
The problems:
Not sure how to stop the server once the file is downloaded on another device
it throws an error if the specified file's name contains non-English characters: Uncaught TypeError: The header content contains invalid characters
download speed is under 25mb/s. Is it because of the method used?
I'm using Node.js HTTP module because I cannot use express module, because webpack throws this error when I require('express'):
./node_modules/http-errors/node_modules/statuses/index.js
Module build failed: Error: ENOENT: no such file or directory,
open 'C:\pathToProject\node_modules\http-errors\node_modules\statuses\index.js'
Question:
Is there a better way to do it?
Code:
const fs = require('fs')
const http = require('http')
const os = require('os')
const path = require('path')
startServer() {
// GETTING NETWORK IP OF THE SERVER (ipv4, e.g. 192.168.0.x)
var interfaces = os.networkInterfaces()
var addresses = []
for (var k in interfaces) {
for (var k2 in interfaces[k]) {
var address = interfaces[k][k2];
if (address.family === 'IPv4' && !address.internal) {
addresses.push(address.address)
}
}
}
var filtered = addresses.filter(x => x.includes("192.168.0"))
// SERVING FILE FOR OTHER LOCAL DEVICES
const hostname = filtered
const port = 8080
var fileName = "1.png"
var filePath = path.join("C:/Users/u/Desktop", fileName)
const server = http.createServer((req, res) => {
var stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
"Content-Disposition": "attachment; filename=" + fileName
});
var readStream = fs.createReadStream(filePath);
// replacing all the event handlers with a simple call to readStream.pipe()
readStream.pipe(res);
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
}

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;.

Node Js : Unable to find error in below file filter code

I have written small code to get files filtered by extension. And my point of view logic is fine but I am unable to point out why I am not getting expected output.
Please have a look.
CODE
var fs = require('fs')
var path = require('path')
path_name = process.argv[2]
ext_name = "."+process.argv[3]
var filter_function = function ( path_name,exthide_name,callback) {
fs.readdir(dirpath,function(err,list) {
if(err) return console.error(err)
for ( var i in list) {
if(path.extname(list[i]) == ext_name)
console.log(list[i])
}
})
}
module.exports=filter_function
Output :
linuxmen#linuxmen-fresh:~/test/test1$ node ownModuleNode.js /home/linuxmen/test/test1/ js
linuxmen#linuxmen-fresh:~/test/test1$
But I have so many files with js extension in that directory.
Proof:
linuxmen#linuxmen-fresh:~/test/test1$ ls *js
check_mod1.js ex1.js ex2.js ex3.js ex4.js ex5.js ex6.js ex7.js ex8.js filter.js filter_use.js modse.js ownModuleNode.js se.js use_mod1.js using_module.js
Could please help , what I am missing.
Update - 1 : I am using above code a module file and calling it here.
File using above code
var mymodule = require('./ownModuleNode')
mymodule.filter_function(process.argv[2],process.argv[3])
Update 2 :
var fs = require('fs')
var path = require('path')
path_name = process.argv[2]
ext_name = "."+process.argv[3]
console.log("path_name :",path_name,"extname:",ext_name)
var filter_function = function ( path_name,ext_name,callback) {
fs.readdir(path_name,function(err,list) {
if (err) console.error(err)
console.log(list)
for ( var i in list) {
if(path.extname(list[i]) == ext_name)
console.log(list[i])
}
})
}
module.exports=filter_function
Output:
linuxmen#linuxmen-fresh:~/test/test1$ node ownModuleNode.js /home/linuxmen/test/test1/ js
pathanme : /home/linuxmen/test/test1/ extname: .js
Thank you.
It looks like you are exporting the function directly. When you require() it, you just getting the function. You'll need to use your module in your application. Put this in 'app.js' in the same dir as ownModuleNode.js:
var filterFunction = require('./ownModuleNode');
filterFunction(process.argv[2], process.argv[3]);
Then call it with:
node app ~/Documents/dev/project .js
Outputs:
app.js
ownModuleNode.js
Note that when you pass the extension, you need the preceding dot because path.extname() returns the dot.

Categories