extract 7zip files in Nodejs - node.js

I am trying to extract .7z files which is password protected.
In a particular folder path there are some .7z files format. First I have to extract all files in the same directory than I have to do another stuff with this files.
const path = require('path')
const fs = require('fs')
import { extractFull } from 'node-7z-forall';
const dirpath = path.join('C:/MyFolder/DATA')
fs.readdir(dirpath, function(err, files) {
const txtFiles = files.filter(el => path.extname(el) === '.7z')
console.log(txtFiles);
extractFull(txtFiles, 'C:/MyFolder/DATA', { p: 'admin123' } /* 7z options/switches */)
.progress(function (files) {
console.log('Some files are extracted: %s', files);
});
})
I am using node-7z-forall module but it is only working when I change the file format to .js to .mjs. in .mjs file format file extract smoothly .but in .js format it is not working.
error:
import { extractFull } from 'node-7z-forall';
^^^^^^
SyntaxError: Cannot use import statement outside a module
How to handle this error. Is it possible to work with in .js format instead of .mjs format?
I am new in nodejs. Please help!

the reason it errors, it that ".js" indicates a commonjs file which uses require() but a ".mjs" file indicates a module which uses the import syntax.
This is also where the error comes from because you try to use import in a non module.
You can prevent the error by simply importing the package using require():
const { extractFull } = require('node-7z-forall');

Related

express-fileupload remove BOM from csv

I am trying to remove the BOM from a csv as express uploads it. To test this I upload a csv that I know it has the BOM. And I upload it normally using express-fileupload.
import fileUpload from 'express-fileupload'
import { resolve } from 'path'
import { writeFile, readFile } from 'fs/promises'
import stripBom from 'strip-bom'
const file = req.files.myfile
file.name = `keywords.csv`
const file_location = resolve('uploads', file.name)
await file.mv(file_location)
When moved to the uploads folder it mantains the BOM. To remove it I write the file after it's moved and use stripBom to remove it, it works but it feels really comvoluted.
...
await file.mv(file_location)
await writeFile(file_location, stripBom(csv))
Is there a way to remove the BOM as the file it's moved?

JSON file not found

I have a json file with the name of email_templates.json placed in the same folder as my js file bootstrap.js. when I try to read the file I get an error.
no such file or directory, open './email_templates.json'
bootstrap.js
"use strict";
const fs = require('fs');
module.exports = async () => {
const { config } = JSON.parse(fs.readFileSync('./email_templates.json'));
console.log(config);
};
email_templates.json
[
{
"name":"vla",
"subject":"test template",
"path": ""
}
]
I am using VS code , for some reason VS code doesnt autocomplete the path as well which is confusing for me.Does anyone know why it is doing this?
Node v:14*
A possible solution is to get the full path (right from C:\, for example, if you are on Windows).
To do this, you first need to import path in your code.
const path = require("path");
Next, we need to join the directory in which the JavaScript file is in and the JSON filename. To do this, we will use the code below.
const jsonPath = path.resolve(__dirname, "email_templates.json");
The resolve() function basically mixes the two paths together to make one complete, valid path.
Finally, you can use this path to pass into readFileSync().
fs.readFileSync(jsonPath);
This should help with finding the path, if the issue was that it didn't like the relative path. The absolute path may help it find the file.
In conclusion, this solution should help with finding the path.

How to export everything from every file in a directory?

Usually, I create an index.js file that exports everything from every file in a specific directory. like this:
export * from "./file1"
export * from "./file2"
export * from "./file3"
This is a common pattern in all of my projects. The downside of this approach is that whenever I create a new file in a directory I have to change its corresponding index.js file and export the new file. Now I'm trying to automate it and write a script that exports everything in every file in a directory.
after some googling, I came up with this:
import fs from "fs";
export let exp = {};
fs.readdirSync("./").forEach(function (file) {
if (file.indexOf(".js") > -1 && file != "index.js") {
const imp = require(`./` + file);
exp = { ...exp, ...imp };
}
});
But it doesn't work, maybe because I used the require function and that doesn't work with ES modules.
Also, I can't write something like this because I'm not allowed to use export in a function block.
export let exp = {};
fs.readdirSync("./").forEach(function (file) {
if (file.indexOf(".ts") > -1 && file != "index.ts") {
export * from ("./"+file);
}
});
So I stock here. do you have any idea about this?
I suggest using a package like glob. The glob package allows you to get all files inside a directory including those hidden within a subfolder.
Example usage:
const glob = require("glob");
glob("**/*", function (err, files) {
// files is an array of filenames
// err is an error object or null
});

typescript cannot recognize .sequelizerc file

I have this .sequelizerc file:
const path = require('path');
module.exports = {
config: path.resolve('.', 'src/config/sequelizeCLIConfig.json'),
'migrations-path': path.resolve('.', 'db', 'migrations'),
};
And then I have a .ts file that generates the cli config file named generateSequelizeCLIConfig.ts, which does the following thing:
import path from 'path';
import fs from 'fs';
import config from '../../src/config';
import sequelizeRC from '../../.sequelizerc';
const env = process.env.NODE_ENV || 'development';
const targetFile = path.resolve(sequelizeRC.config);
const sequelizeCLIConfig: Record<string, any> = {};
sequelizeCLIConfig[env] = config.db;
fs.writeFile(targetFile, JSON.stringify(sequelizeCLIConfig, null, 4), err => {
if (err) {
return console.log(err);
}
console.log('The sequelizeCLI config file was saved at ' + targetFile + '!');
});
The plan is, every time I need migration, I run this script first. This script grabs the data from the config folder and generate the src/config/sequelizeCLIConfig.json. And then I run the migration with config data from this .json file.
So the file structure is this:
-.sequelizerc
-db
|-scripts
|-generateSequelizeCLIConfig.ts
-src
|-config
|-index.ts
.sequelizerc
However I got this error when compiling generateSequelizeCLIConfig.ts:
TSError: тип Unable to compile TypeScript:
db/scripts/generateSequelizeCLIConfig.ts(4,25): error TS2307: Cannot find module '../../.sequelizerc'.
So it seems .sequrlizerc is not recognized although I have double checked that this file does exist.
My guess is, .sequelizerc behind the scene is a .js file, not a .ts file, and this gives me some trouble. But I don't know how to verify this, nor how to fix it.
Any suggestions?
Try to add the .sequelizerc to your include in your tsconfig as follows:
{
..prev configs...,
include: [ ...your paths..., ".sequelizerc"],
}
Delete dot. Rename the .sequelizerc to sequelizerc

Can't find the file I created by fs.writeFile

I am trying to write a file in node.js using fs.writeFile, I use the following code:
const fs = require('filer');
const jsonString = JSON.stringify(myObj)
fs.writeFile('/myFile.txt', jsonString, function (err) {
if (err) throw err;
console.log('Saved!');
});
}
I am sure the file is created, because I can read it by fs.readFile referring to the same address, but I cannot find it on the disk by using windows search. What I understood, if I change the localhost port it saves the files in another location. I already tried "process.cwd()", but it didn't work.
I really appreciate it if someone could help.
try to use : __dirname instead of process.cwd()
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, '/myFile.txt');
console.log(filePath);
const jsonString = JSON.stringify({ name: "kalo" })
fs.writeFile(filePath, jsonString, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
And I would like to know why are you using 'filer' instead of default fs module?
fs module is native module that provides file handling in node js. so you don't need to install it specifically. This code perfectly worked and it prints absolute location of the file as well.Just run this code if it doesn't work, I think you should re install node js. I have updated the answer.You can also use fs.writeFileSync method as well.
From documentation: "String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as determined by calling process.cwd()."
So in order to determine your working directory (i.e. where fs create files by default) call (works for me):
console.log(process.cwd());
Then if you would like to change your working directory, you can call (works for me as well):
process.chdir('path_to_new_directory');
Path can be relative or absolute.
This is also from documentation: "The process.chdir() method changes the current working directory of the Node.js process or throws an exception if doing so fails (for instance, if the specified directory does not exist)."

Resources