Binary file in npm package - javascript

I try to create an npm package, which can be started as a command from shell. I have package.json
{
"name": "myapp",
"version": "0.0.6",
"dependencies": {
"async": "",
"watch": "",
"node-promise": "",
"rmdir": "",
"should": "",
"websocket": ""
},
"bin": "myapp"
}
and myapp
#!/bin/bash
path=`dirname "$0"`
file="/myapp.js"
node $path$file $1 &
But I get an error:
module.js:340
throw err;
^
Error: Cannot find module '/usr/local/bin/myapp.js'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
The problem is that myapp.js is in another directory. How can I get this directory name from my script? Or maybe there is better way to do this?

Actually, you can put your myapp.js file into bin.
So, the bin key in package.json file should be like this :
"bin": { "myapp" : "<relative_path_to_myapp.js>/lib/myapp.js" }
At the first line in myapp.js, you must add this shebang line :
#!/usr/bin/env node
It tells the system to use node to run myapp.js.
... Or if you don't want to call myapp.js directly, you can create a script like this to be your executable file :
#!/usr/bin/env node
var myapp = require('<relative_path_to_myapp.js>/myapp.js');
myapp.doSth();
and in package.json :
"bin" : { "myapp" : "<relative_path_to_the_script>/script.js" }
By doing this either way, you can avoid finding the path to your nodemodule.
But... if you insist to use your old myapp bash script, then you can find the path to the module with this :
myapp_path=$( npm explore -g myapp -- "pwd" )
Hope these help :D

https://docs.npmjs.com/files/package.json#bin
From the above link:
...
To use this, supply a bin field in your package.json which is a map of command name to local file name. On install, npm will symlink that file into prefix/bin for global installs, or ./node_modules/.bin/ for local installs.
For example, myapp could have this:
{ "bin" : { "myapp" : "./cli.js" } }
So, when you install myapp, it’ll create a symlink from the cli.js script to /usr/local/bin/myapp.
...

Related

anchor test command error - Error: Cannot find module '[#project-serum/anchor] ' Please verify that the package.json has a valid "main" entry

I was following an introduction tutorial using anchor (solana framework), it is based in the official github.
In the testing part, I used anchor test command and I got this error:
BPF SDK: /home/sebastian/.local/share/solana/install/releases/1.9.12/solana-release/bin/sdk/bpf
cargo-build-bpf child: rustup toolchain list -v
cargo-build-bpf child: cargo +bpf build --target bpfel-unknown-unknown --release
Finished release [optimized] target(s) in 3.86s
cargo-build-bpf child: /home/sebastian/.local/share/solana/install/releases/1.9.12/solana-release/bin/sdk/bpf/dependencies/bpf-tools/llvm/bin/llvm-readelf --dyn-symbols /home/sebastian/Documentos/solana-project/anchor/examples/tutorial/basic-1/target/deploy/basic_1.so
To deploy this program:
$ solana program deploy /home/sebastian/Documentos/solana-project/anchor/examples/tutorial/basic-1/target/deploy/basic_1.so
The program address will default to this keypair (override with --program-id):
/home/sebastian/Documentos/solana-project/anchor/examples/tutorial/basic-1/target/deploy/basic_1-keypair.json
yarn run v1.22.17
$ /home/sebastian/Documentos/solana-project/anchor/examples/tutorial/node_modules/.bin/mocha -t 1000000 tests/
Error: Cannot find module '/home/sebastian/Documentos/solana-project/anchor/examples/tutorial/node_modules/#project-serum/anchor/dist/cjs/index.js'. Please verify that the package.json has a valid "main" entry
at tryPackage (node:internal/modules/cjs/loader:353:19)
at Function.Module._findPath (node:internal/modules/cjs/loader:566:18)
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/home/sebastian/Documentos/solana-project/anchor/examples/tutorial/basic-1/tests/basic-1.js:2:16)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
at async formattedImport (/home/sebastian/Documentos/solana-project/anchor/examples/tutorial/node_modules/mocha/lib/nodejs/esm-utils.js:7:14)
at async Object.exports.requireOrImport (/home/sebastian/Documentos/solana-project/anchor/examples/tutorial/node_modules/mocha/lib/nodejs/esm-utils.js:48:32)
at async Object.exports.loadFilesAsync (/home/sebastian/Documentos/solana-project/anchor/examples/tutorial/node_modules/mocha/lib/nodejs/esm-utils.js:88:20)
at async singleRun (/home/sebastian/Documentos/solana-project/anchor/examples/tutorial/node_modules/mocha/lib/cli/run-helpers.js:125:3)
at async Object.exports.handler (/home/sebastian/Documentos/solana-project/anchor/examples/tutorial/node_modules/mocha/lib/cli/run.js:374:5)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
This is my package.json:
{
"name": "basic-1",
"version": "0.24.2",
"license": "(MIT OR Apache-2.0)",
"homepage": "https://github.com/project-serum/anchor#readme",
"bugs": {
"url": "https://github.com/project-serum/anchor/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/project-serum/anchor.git"
},
"engines": {
"node": ">=11"
},
"scripts": {
"test": "anchor test --skip-lint"
},
"dependencies": {
"#project-serum/anchor": "^0.24.2"
}
}
I really appreciate any information about it. I also attach the tutorial and anchor's github link.
https://github.com/project-serum/anchor
https://youtu.be/CmG5_sIas1Q
Try re-installing #project-serum/anchor
yarn add #project-serum/anchor
In your anchor.toml file, try changing the value of 'test' to mocha tests/test.js , replace test.js with whatever the name of your file in tests.
Go check node_modules/#project-serum/anchor if you don't have a "dist" folder there you will have to run yarn add#project-serum/anchor again. When you can see that the "dist" folder was properly installed you'll be able to run your tests again.

TypeError: Cannot read property 'compile' of undefined

I'm currently trying to follow this tutorial for Ethereum Solidity coding, and for the following code:
const path = require('path');
const fs = require('fs'); // File system module
const solc = require('solc').default; // Solidity Compiler module
// Note that phrase resolving a link means to substitute the actual location in the file system for the symbolic link
// If we assume that logFile is a symbolic link to dir/logs/HomeLogFile, then resolving it yields dir/logs/HomeLogFile
// Generates a path that points directly to the inbox file. __dirname will be the root direction
// inboxPath = desktop/inbox/contracts/inbox.sol
const inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol');
// The next step is to actually read the contents of the source file now
// utf8 is the encoding to read the file's content
const source = fs.readFileSync(inboxPath, 'utf8');
// Call solc.compile and pass in our source code, with only 1 contract
// console.log() means put the output in the console
console.log(solc.compile(source, 1));
I get the following error when I hover over const solc = require('solc').default:
Could not find a declaration file for module 'solc'. 'c:/Users/Hana PC/Desktop/inbox/node_modules/solc/index.js' implicitly has an 'any' type.
Try `npm i --save-dev #types/solc` if it exists or add a new declaration (.d.ts) file containing `declare module 'solc';`ts(7016)
When I try node compile.js, I get:
C:\Users\Hana PC\Desktop\inbox\compile.js:18
console.log(solc.compile(source, 1));
^
TypeError: Cannot read property 'compile' of undefined
at Object.<anonymous> (C:\Users\Hana PC\Desktop\inbox\compile.js:18:18)
[90m at Module._compile (internal/modules/cjs/loader.js:1063:30)[39m
[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)[39m
[90m at Module.load (internal/modules/cjs/loader.js:928:32)[39m
[90m at Function.Module._load (internal/modules/cjs/loader.js:769:14)[39m
[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)[39m
[90m at internal/main/run_main_module.js:17:47[39m
I've never used/interacted with TypeScript or JavaScript or anything of the sorts, so I honestly don't even know what this error means. I've already tried uninstalling and reinstalling solc multiple times, all to no avail.
My node.js version is:
6.14.8
I tried doing some searching online for what the implicitly has an 'any' type. means or how it could be fixed, but I honestly didn't get any of it. If it helps, my package.json looks like this:
{
"name": "inbox",
"version": "1.0.0",
"description": "",
"main": "compile.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"solc": "^0.8.0"
}
}
Any help is appreciated!
**** Update:**
Tried it with uninstall solc and a fresh install (without using version 0.4.17), and got an Assertion Error:
assert.js:383
throw err;
^
AssertionError [ERR_ASSERTION]: Invalid callback object specified.
at runWithCallbacks (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:97:7)
at compileStandard (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:207:14)
at Object.compileStandardWrapper [as compile] (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:214:14)
Wish I knew what was goin on
As per the discussion we had above, since the solidity file is using v0.4.17, you should use the same version of solc library in your code.
I have created a working example of your code here and the only two changes required were:
Making sure I use v0.4.17 of solc.
Import const solc = require("solc"); and not const solc = require("solc").default;
If you are having trouble downgrading the solc package, then
Delete package-lock.json file and node_modules/ folder.
Update the package.json files dependency to "solc": "0.4.17" and not to "^0.4.17"
Simply run npm install one last time.
This should be enough to get you up and running.

How to use tsify with watchify on Ubuntu?

The input directory contains:
a JavaScript file (a jQuery plugin that is not in the DefinitelyTyped repo) and
2 TypeScript files
declarations.d.ts
main.ts
The tsconfig.json file is this (work in progress):
{
"compilerOptions": {
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"outDir": "wp-content/themes/custom-theme/assets/js",
"watch": true,
"allowJs": true,
"lib": ["ES2016", "DOM"]
},
"include": [
"wp-content/themes/custom-theme/assets/ts"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
Currently I have this watch.sh script that works well:
tmux \
new-session 'cd html && tsc' \; \
split-window 'cd html/wp-content/themes && scss --watch custom-theme/assets/scss:custom-theme/assets/css' \; \
split-window 'cd html/wp-content/themes && watchify custom-theme/assets/js/main.js -o custom-theme/assets/js/bundle.js'
I want to replace this script with something like a Browserify build.js file (I prefer build.ts if possible), and I want to use Tsify with Watchify (I understood that Watchify build.js file is similar to the Browserify file).
I have seen this example, but I am not sure if I am on the good road.
I have this not-working build.js file:
const browserify = require("browserify");
const tsify = require("tsify");
browserify()
.plugin(tsify, { allowsJs: true })
.add("wp-content/themes/custom-theme/assets/ts/main.ts")
.bundle()
.on('error', function (error) { console.error(error.toString()) })
.pipe(process.stdout);
It does not even start to run: it says there is a syntax error on line 1 near (.
Any advice is greatly appreciated.
Thank you.
Update 1
The new build.js file:
const watchify = require("watchify");
const tsify = require("tsify");
watchify()
.plugin(tsify, { allowsJs: true })
.add("wp-content/themes/custom-theme/assets/ts/main.ts")
.bundle()
.on('error', function (error) { console.error(error.toString()) })
.pipe(process.stdout);
runs but throws this:
$ node build.js
/.../node_modules/watchify/index.js:14
var cache = b._options.cache;
^
TypeError: Cannot read property '_options' of undefined
at watchify (/.../node_modules/watchify/index.js:14:19)
at Object.<anonymous> (/.../build.js:4:1)
at Module._compile (internal/modules/cjs/loader.js:1147:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
at Module.load (internal/modules/cjs/loader.js:996:32)
at Function.Module._load (internal/modules/cjs/loader.js:896:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
Update 2
I ended up using this watch.sh shell script file:
tmux \
new-session 'cd html && tsc' \; \
split-window 'cd html/wp-content/themes; scss --watch custom-theme/assets/scss:custom-theme/assets/css' \; \
split-window 'cd html/wp-content/themes; watchify custom-theme/assets/ts/main.ts -p [ tsify ] -o custom-theme/assets/js/bundle.js -v'
From here I understand that it respects the tsconfig.json file. The only issue is that the require call in main.ts does not return something that VS Code understands well, so I do not have autocompletition support. This is where I still need help. In future I would also like to use a build.js script, if there is anyone who can help me with this.
Now I use ES6 syntax for importing modules everywhere I import something. I also use relative paths to files inside the relevant npm packages in node_modules directory when I import from npm packages.
In tsconfig.json I have these lines besides others:
"target": "ES3",
"lib": ["ES2020", "DOM"],
"module": "CommonJS"
The final working test project is here.
I still have problems with some modules that are not prepaired for ES6 import.

Argument passing to PM2

I want to put in production a node service :
When I launch my application with my arguments like that : node ./backend -c "uf4m6fhnh" -s "SPNLGZsUoSpQ=" -o "8696". Everything works well.
Now I want to put it in production with PM2 :
I have tried the 2 ways to to that (CLI and JSON file) like that :
CLI version :
pm2 start backend.js --node-args="-c uf4lvm6fhnh -s SPNLGZsUoSpQ= -o 8696" --name MyAppName
and also :
pm2 start backend.js --name MyAppName -- "-c uf4lvm6fhnh -s SPNLGZsUoSpQ= -o 8696"
Config file (JSON) :
{
"apps": [
{
"name": "MyAppName ",
"script": "./backend.js",
"node_args": [
"-c",
"uf4lvm6fhnh",
"-s",
"SPNLGZsUoSpQ=",
"-o",
"8696"
]
}
]
}
and then : pm2 start myConfigJson.json
For each of this possible solution, I have the same error in my pm2 logs :
Error: Cannot find module '/home/me/Projects/Project/uf4lvm6fhnh'
(Note that the not found module is my passed argument)
Any ideas ?
Use args instead.
node_args is an alias to interpreter_args which passes arguments to node itself, rather than the script. As a result, your command line ends up calling -c|--check on node itself instead.
See http://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/#programmatic-api and https://nodejs.org/api/cli.html#cli_c_check

not able to require publish module

Im was publish module to npm (very simple module for testing purpose) and it seems that I was not able to require it.
when I do npm install --save I saw that the package is located inside the node_modules (and new entry was created in the package.json) folder and in my server.js file I do
var myModule = require('nodewrapapp');
and I got the following error:
Error: Cannot find module 'nodewrapapp'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:289:25)
at Module.require (module.js:366:17)
The module contain only one very simple file :
function startInterval(fn) {
fn(); // do the function right now
return setInterval.apply(this, arguments); // defer to setInterval
}
module.exports = startInterval; // let me be required
what am I doing wrong here?
Change your main to server.js
{
"name": "nodewrapapp",
"version": "0.0.1",
"description": "test",
"main": "server.js", // Here
...
}

Categories

Resources