I tried many ways available in different sites to unzip the downloaded zipped folder and found the below one is simplest way.However, am facing the below issue.Please help me resolve this :
const extract = require('extract-zip');
const path = require('path');
unzip=async function(){
let source = "Downloads/sample.zip";
let destination = "Downloads/";
let sP = path.resolve(source);
console.log("Source path : " +sP);
let dP = path.resolve(destination);
console.log("Destination path : " +dP);
await extract(sP, { dir: dP });
console.log('Extraction complete');
}
Output :
Source path : /Users/myName/Documents/framework/Downloads/sample.zip
Destination path :/Users/myName/Documents/framework/Downloads
.
.
Error: absolute path://sample/
The resolved path should be relative to the path of the directory where the code is being executed.
Replace
let source = '../../Downloads/sample.zip
let destination = '../../Downloads
let sP = path.resolve(source);
let dP = path.resolve(destination);
The problem is the .zip file itself starting with //. Extract-zip uses yauzl which throws an exception if it's an absolute path:
https://github.com/thejoshwolfe/yauzl/issues/135
Related
I am attempting to do a file search based off array of file names and root directory. I found some file search snips online that seem to work when I am finding just 1 single file, but it will not work when there is more than 1 file specified. Below is the snippet:
const fs = require('fs');
const path = require('path');
var dir = '<SOME ROOT DIRECTORY>';
var file = 'Hello_World.txt'
var fileArr = ['Hello_World.txt', 'Hello_World2.txt', 'Hello_World3.txt'];
const findFile = function (dir, pattern) {
var results = [];
fs.readdirSync(dir).forEach(function (dirInner) {
dirInner = path.resolve(dir, dirInner);
var stat = fs.statSync(dirInner);
if (stat.isDirectory()) {
results = results.concat(findFile(dirInner, pattern));
}
if (stat.isFile() && dirInner.endsWith(pattern)) {
results.push(dirInner);
}
});
return results;
};
console.log(findFile(dir, file));
Any thoughts on how I can get this working with an array rather than just a single file string?
Doing the following seems to be working, but didn't know if there were other ways to do this which may be simpler:
newFileArr = [];
fileArr.forEach((file => {
//findFile(dir, file).toString();
console.log(findFile(dir, file).toString());
}));
The only thing that needs to change is the condition to determine if an individual filepath meets the search criteria. In the code you've posted, it looks like dirInner.endsWith(pattern), which says "does the filepath end with the given pattern?"
We want to change that to say "does the filepath end with any of the given patterns?" And closer to how the code will look, we can rephrase that as "Can we find a given pattern such that the filepath ends with that pattern?"
Let's rename pattern to patterns. Then we can simple replace dirInner.endsWith(patterns) with patterns.some(pattern => dirInner.endsWith(pattern))
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.
I have an application which uploads csv file into a particular folder, say, "uploads".
Now I want to get the full path of that csv file, for example, D:\MyNodeApp\uploads\Test.csv.
How do I get the file location in Node.js? I used multer to upload file.
var path = require("path");
var absolutePath = path.resolve("Relative file path");
You dir structure for example:
C:->WebServer->Public->Uploads->MyFile.csv
and your working directory would be Public for example, path.resolve would be like that.
path.resolve("./Uploads/MyFile.csv");
POSIX home/WebServer/Public/Uploads/MyFile.csv
WINDOWS C:\WebServer\Public\Uploads\MyFile.csv
this solution is multiplatform and allows your application to work on both windows and posix machines.
Get all files from folder and print each file description.
const path = require( "path" );
const fs = require( 'fs' );
const log = console.log;
const folder = './';
fs.readdirSync( folder ).forEach( file => {
const extname = path.extname( file );
const filename = path.basename( file, extname );
const absolutePath = path.resolve( folder, file );
log( "File : ", file );
log( "filename : ", filename );
log( "extname : ", extname );
log( "absolutePath : ", absolutePath);
});
Assuming you are using multer with express, try this in your controller method:
var path = require('path');
//gets your app's root path
var root = path.dirname(require.main.filename)
// joins uploaded file path with root. replace filename with your input field name
var absolutePath = path.join(root,req.files['filename'].path)
In TypeScript, I did the following based on the relative file path.
import { resolve } from 'path';
public getValidFileToUpload(): string {
return resolve('src/assets/validFilePath/testFile.csv');
}
If you are using a "dirent" type:
const path = require( "path" );
full_path = path.resolve( path_to_folder_containing__dir_ent__ , dir_ent.name );
Class: fs.Dirent
https://nodejs.org/api/fs.html#fs_dirent_name
Module: fs.path
https://nodejs.org/api/path.html
I think the simplest option is:
dirname module: https://nodejs.org/docs/latest/api/modules.html#modules_dirname
filename: https://nodejs.org/docs/latest/api/modules.html#modules_filename
console.log(__dirname)
console.log(__filename)
I am writing a meteor package 'myPackage' which needs to write a file onto disk using Npm FileSystem and Pah modules.
The file should end up in the example-app/packages/myPackage/auto_generated/myFile.js, where example-app project
has myPackage added.
fs = Npm.require( 'fs' ) ;
path = Npm.require( 'path' ) ;
Meteor.methods( {
autoGenerate : function( script ) {
var myPath = '/Users/martinfox/tmp/auto-generated' ;
var filePath = path.join(myPath, 'myFile.js' ) ;
console.log( filePath ) ; // shows /Uses/martinfox/tmp/auto-generated/myFile.js
var buffer = new Buffer( script ) ;
fs.writeFileSync( filePath, buffer ) ;
},
} );
When I run the code above (server side only) I get
Exception while invoking method 'autoGenerate' Error: ENOENT,
no such file or directory '/Uses/martinfox/tmp/auto-generated/myFile.js'
Note /Uses/martinfox/tmp/auto-generated folder does exist
Any ideas what is going wrong?
Is it possible to obtain the absolute path to the meteor projects directory?
To get the path of your project you can do this :
from main.js stored in the root of your app
var fs = Npm.require('fs');
__ROOT_APP_PATH__ = fs.realpathSync('.');
console.log(__ROOT_APP_PATH__);
You can also check if your folder exists :
if (!fs.existsSync(myPath)) {
throw new Error(myPath + " does not exists");
}
Hope it will help you
If you are just looking for the absolute path for your app, you could simply do var base = process.env.PWD, which yields: /Users/[username]/[app-name]
This would avoid the extra stuff .meteor/local/build/programs/server
I am working on creating my first Node.js module, and am having a difficult time trying to decide the best way to handle this. What is the recommended method for receiving paths to files to my module as input by the user? How can I then resolve where that is? Where the user called my module and the location of my running code are in two different places.
Let's take this a step further. Let's say a user has a JSON config file with an array of these paths (in config/settings.json):
{
"paths": [
"../path1",
"path2",
"/path/to/path3",
"~/path4"
]
}
Now obviously these paths are relative to the config file, not any executing code. This feels wrong, as now my method must accept the __dirname, the path of the config file relative to __dirname, etc.
var mymodule = require('mine');
mymodule(__dirname, './config/settings.json');
Any files I read from the config must then be based on the location of this config file. This feels weird. Suggestions?
From FileUtils source:
var updateFileProperties = function (file, path){
file._path = null;
file._usablePath = null;
file._isAbsolute = false;
if (path === undefined || path === null) return;
path = PATH.normalize (path);
var index = path.indexOf (":") + 1;
var windowsRoot = path.substring (0, index);
path = path.substring (index);
//https://github.com/joyent/node/issues/3066
if (path[0] === "/" && path[1] === "/"){
path = path.replace (/[\/]/g, "\\");
path = path.substring (0, path.length - 1);
}
file._isAbsolute = path[0] === SLASH;
file._path = windowsRoot + path;
file._usablePath = file._isAbsolute ? file._path : (windowsRoot + PATH.join (file._relative, path));
};
var File = function (path){
var main = process.mainModule.filename;
var cwd = main.substring (0, main.lastIndexOf (SLASH));
var relative = PATH.relative (process.cwd (), cwd);
this._relative = relative;
//...omitted
updateFileProperties (this, path);
};
This piece of code resolves the relative path problem.
_usablePath contains the real path. The "." path will be the directory where the main file is located. No matter how is called, it will point to the expected directory.
You can test the functions printing what the new File (<path>).getPath () returns.
I would avoid complexity and go for absolute paths only. Most users do __dirname + '../relativepath' anyways. ( at least that's what I do ).