My cli engine(npm package) cant find path to read file when install on another folder - node.js

I am building an app that auto completes some type of file. When i run node index.js in the program folder i get the correct i results.
Although i want to make it an npm package that can work as a cli engine. For example i want to write the command generate and the code to produce the results.
In order to auto complete the file i have to read some data that i have stored in a .csv file that comes along with my program.
When i try to run generate command under another folder it can read that file.
I am very new to cli and i don't understand yet quite well how thing work.
Thanks in advance for the help.
Here is the code of my cli conversion.
#!/usr/bin/env node
const program = require("commander");
const {
predict
} = require("./classifier");
program.version("1.0.0").description("ESLint Rules Generator");
program
.command("generate")
.description("Generate ESLint Rules")
.action(() => {
predict();
});
program.parse(process.argv);
Here is the problematic line:
let str = fs.readFileSync("data_files/rules.csv", "utf-8");
This is the error i get: ENOENT: no such file or directory, open 'data_files/rules.csv'

Related

How to use docx npm package in production to save a file

I am generating a doc file using docx-template npm package in node js. and the file is getting successfully saved in my backend/controller folder on my local machine. Now i want to do prod deployment on Heroku but i dont know what path has to be set to save the file in production.
I have used 'fs' module to read and write file. Shown below.
fs.writeFileSync(
path.resolve(__dirname, `${contractName} ${element.frequency}.docx`),
buffer
);
You probably have to use the "send(Buffer)" feature of express.
See the following page :
https://expressjs.com/en/api.html#res.send
const contentTypes = {
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
};
res.set('Content-Type', contentTypes.docx);
res.send(buffer);
This is because the "fs" module is used to write the data on the disk, but if it is in production, most likely what you want is to let the user "download" a file, and that is done using res.send() which takes as an argument a Buffer to achieve this feature.

node.js reading ts file as js in the npm root directory

I've got a Nodejs CLI written with typescript. It is dynamically reading an external file init.ts.
const {init} = require(initFunctionFile)
The goal is that other packages can run the CLI using their own init.ts file. If init.ts is in a plain directory, it works fine. But if it's in the global npm root directory, or if a package containing init.ts is not stored locally and is executed using npx, I'm getting the error:
~/.nvm/versions/node/v14.9.0/lib/node_modules/package-name/.../init.ts:5
init: async function(command: string, codeDir: string){
^
SyntaxError: Unexpected token ':'
It seems that node thinks the file is js. What is happening here, and what's a better way to do this?

PythonBridge: how to correctly set up current working directory of the child process?

I have a Node.js project which must be integrated with a previously written Python script. Currently Node.js project is deployed in such a way that the Python script must be placed inside of the Node root directory. Under these conditions the whole project runs well and there are no error warnings. For some reasons, I would like to put the Python script outside of the Node root directory. Thus, I have added .cwd parameter:
const python = pythonBridge({
python: 'python3',
stdio: ['pipe', 'pipe', 'pipe'],
cwd: '/dir1/dir2/' # added line
})
Now when the Python script is inside of /dir1/dir2/ folder, an error message is generated:
ERROR: (node:14870) UnhandledPromiseRejectionWarning: ReferenceError: logger is not defined
at /NodeJSrootFolder/dist/NodeJSFactory.js:69:7
Being a newcomer in Node.js, I would like to know besides .cwd which parameters must be changed in order to make project run correctly?
According to the instructions posted here (https://www.npmjs.com/package/python-bridge), current working directory of the child process must be specified via .cwd option:
var python = pythonBridge(options)
options.cwd - String Current working directory of the child process
As I have mentioned in my question, this solution doesn't work. Actually, .js file ignore .cwd option and looks for the Python script inside of the Node.js root directory. In order to resolve the problem, the full address must be specified inside of the FS object:
const fs = require('fs').promises
// ...
// somewhere below
// ...
let reads = [
fs.readFile('/dir1/dir2/myPythonScript.py'),] // vs. fs.readFile('./myPythonScript.py')
I am not sure whether it is a normal procedure or some dirty hack, but it works for my project.

Opening an excel file with opn while another excel file is open, will execute code immediately without waiting

I'm using a library called opn. This makes it easier to spawn a child process to open a file in the main process of electron. I could use shell but I need to be able to detect when the file is closed which shell API doesn't provide.
Whenever I open an excel file and there are no other excel files opened, it will work fine and it will wait until I close the file before it resolve the promise. However, if there are other excel files open then it won't wait for the file to be closed and it will resolve the promise immediately.
I did some digging in the source code of the library and the command used to open the file is this for windows: start "" /wait name_of_file where name_of_file is a place holder for the file. The actual command the library executes is different but this one is enough for my use case. I ran into the same problem even when doing it manually without using the library. Maybe I should post this under super user instead of stackoverflow.
Here is the code that opens the file, wait for the file then executes callback.
opn(file, { app: 'EXCEL', wait: true }).then(() => {
const stream = fs.createReadStream(file);
papa.parse(stream, {
delimiter: ',',
complete: (results) => {
mainWindow.webContents.send('uploadNewIndexFileRen', key,
results.data);
},
error: (err) => {
throw err;
}
});
}).catch((error) => { throw error; });
UPDATE:
Here is a quick nodejs repo. All you need to do is clone/fork to check the problem or make a pull request then do npm install to download needed packages. To reproduce the exact problem that I have you might need to be in the following software versions:
Window 10
npm 5.5.1
node v8.9.1
excel 2013
opn 5.2.0 as seen in package.json
This is probably due to the way Excel handles files. I'm guessing Excel handles files with a single process so subsequent opening of files simply signals to the existing process that another files needs opening before closing.
You may be able to force Excel to open a new instance for each file by following these instructions.
Apparently using the /x command line switch will also start a new process:
excel.exe /x

Copy contents of image file to the clipboard using gulp

I'm writing a gulp task to do the following:
Watch an image file for changes
If image file has changed, copy the contents of the image to the clipboard, ready for me to paste.
Note: I'm on Windows and am using nircmd.exe to do the copy of the image contents. The following command line works for me:
nircmd.exe clipboard copyimage "G:\IMG\pic.png"
I've put this into a .bat file so I can run the file via commandline.
My gulpfile (so far):
var gulp = require('gulp'),
watch = require('gulp-watch'),
shell = require('gulp-shell'),
run = require('gulp-run'),
clipboard = require("gulp-clipboard"),
myTerminal = require("child_process").exec,
commandToBeExecuted = "./copy-to-clipboard.bat";
gulp.task('copy-to-clipboard', function () {
require('child_process').spawn('cmd', ['/s', '/c', '"G:\\Git\\copy-to-clipboard\\copy-to-clipboard.bat"'], {
windowsVerbatimArguments: true
});
});
gulp.task('default', function () {
watch('watch/*.png','copy-to-clipboard');
});
I've tried gulp-shell but since this opens a node terminal, nircmd.exe is not recognised as an internal or external command.
I've also tried child_process (both spawn and exec), but while I get no errors, the contents are still not in the clipboard.
Is there an easier way or is this just not possible?
Thanks in advance!
It sounds like its trying to run it if you are getting a
nircmd.exe is not recognised as an internal or external command.
error.
I would add nircmd.exe to your path to fix it.
or in your bat file you could do something like:
c:\path\to\program\nircmd.exe
that might fix it to.
If you are going to use nircmd that much I would just add it to your path.

Resources