Common issues and solutions when using @socketsecurity/lib.
Problem: Cannot find module '@socketsecurity/lib/...' after installation.
Solution:
-
Verify the package is installed:
npm list @socketsecurity/lib
-
Check your import path uses the correct export:
// Correct import { Spinner } from '@socketsecurity/lib/spinner' // Wrong import { Spinner } from '@socketsecurity/lib'
-
Clear your package manager cache and reinstall:
# npm rm -rf node_modules package-lock.json npm install # pnpm rm -rf node_modules pnpm-lock.yaml pnpm install # yarn rm -rf node_modules yarn.lock yarn install
Problem: TypeScript reports "Could not find a declaration file for module '@socketsecurity/lib/...'"
Solution:
-
Ensure you're using Node.js 22+ (required by the library)
-
Check your
tsconfig.jsonhas proper module resolution:{ "compilerOptions": { "moduleResolution": "node", "esModuleInterop": true } } -
Restart your TypeScript server in your editor
Problem: Spinner text appears but doesn't animate.
Solution:
Make sure you called .start():
const spinner = Spinner({ text: 'Loading...' })
spinner.start() // Required!Problem: Text remnants left after spinner stops.
Solution:
Use the *AndStop methods:
// Good
spinner.successAndStop('Done')
// Avoid
spinner.success('Done')
spinner.stop()Problem: Spinner mixes with command stdout/stderr.
Solution: Pass the spinner to spawn options:
const spinner = Spinner({ text: 'Running command...' })
spinner.start()
await spawn('command', [], {
stdio: 'inherit', // Spinner auto-pauses
spinner,
})
spinner.successAndStop('Complete')Problem: File or directory doesn't exist.
Solutions:
For missing files:
// Use safe version that returns undefined
const content = await safeReadFile('./optional-file.txt')
if (content === undefined) {
// Handle missing file
}For missing directories:
// Create directory before writing
await safeMkdir('./path/to/dir')
await writeJson('./path/to/dir/file.json', data)Problem: Insufficient permissions to read/write.
Solutions:
Check file permissions:
# Unix/Linux/macOS
ls -la filename
# Fix permissions
chmod 644 filename # For files
chmod 755 dirname # For directoriesFor safeDelete(), ensure parent directory is writable:
chmod 755 parent-directoryProblem: Paths with backslashes don't work.
Solution:
Always use path.join() for cross-platform paths:
import path from 'node:path'
// Good
const filePath = path.join(dir, 'subdir', 'file.txt')
// Bad (fails on Windows)
const filePath = `${dir}/subdir/file.txt`Problem: readJson() throws SyntaxError.
Solutions:
-
Use
throws: falseto handle gracefully:const data = await readJson('./config.json', { throws: false }) if (data === undefined) { console.log('Using defaults') }
-
Validate JSON syntax:
# Check JSON is valid cat file.json | jq .
-
Common JSON errors:
- Trailing commas (not allowed in JSON)
- Single quotes instead of double quotes
- Missing closing brackets/braces
Problem: Cannot resolve hostname.
Solutions:
- Check the URL is correct
- Verify network connection:
ping example.com
- Check DNS:
nslookup example.com
- Try a different DNS server (8.8.8.8 or 1.1.1.1)
Problem: Server not accepting connections.
Solutions:
- Verify the server is running
- Check the port is correct
- Ensure firewall isn't blocking
- Try accessing in browser first
Problem: Request exceeded timeout.
Solutions:
// Increase timeout
await httpJson('https://api.example.com/slow', {
timeout: 60000, // 1 minute instead of 30s default
})
// Add retries for unreliable networks
await httpJson('https://api.example.com/data', {
retries: 3,
retryDelay: 2000,
})Problem: Exceeded maxRedirects limit.
Solutions:
// Increase limit if redirects are legitimate
await httpDownload(url, dest, {
maxRedirects: 10,
})
// Or disable redirects to debug
const response = await httpRequest(url, {
followRedirects: false,
})
console.log('Redirect location:', response.headers['location'])Problem: Self-signed certificates or certificate validation errors.
Solution: For development only (NOT production):
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'Better solution: Install proper SSL certificates or use a certificate authority.
Problem: ENOENT error when spawning.
Solutions:
-
Check command exists in PATH:
# Unix which command-name # Windows where command-name
-
Use full path:
await spawn('/usr/local/bin/command', [])
-
For Windows
.cmd/.batfiles:await spawn('command.cmd', [], { shell: true, // Required on Windows })
Problem: Spawn never resolves.
Solutions:
-
Add timeout:
await spawn('command', [], { timeout: 30000, // Kill after 30s })
-
Check stdio configuration:
// If command waits for input, ignore stdin await spawn('command', [], { stdio: ['ignore', 'pipe', 'pipe'], })
Problem: Command can't find files.
Solution:
Always use cwd option:
await spawn('npm', ['test'], {
cwd: '/absolute/path/to/project',
})Never use process.chdir() - it's dangerous in Node.js.
Problem: Command doesn't see expected env vars.
Solution: Merge with process.env:
await spawn('command', [], {
env: {
...process.env,
CUSTOM_VAR: 'value',
},
})Problem: getCI() returns false in CI.
Solutions:
-
Check CI sets the
CIvariable:echo $CI
-
Manually set in CI config:
# GitHub Actions env: CI: true # GitLab CI variables: CI: 'true'
-
Most major CI systems (GitHub Actions, GitLab CI, CircleCI, Travis CI) automatically set
CI=true
Problem: Getter returns undefined when var should be set.
Solutions:
-
Verify variable is set:
echo $VAR_NAME
-
Ensure it's exported:
export VAR_NAME=value -
Check spelling and case
Problem: TypeScript complains about unknown types.
Solution: Use type assertions or generics:
// With generic
const data = await httpJson<MyType>('https://api.example.com/data')
// With type assertion
const data = (await httpJson('https://api.example.com/data')) as MyType
// With validation
const data = await httpJson('https://api.example.com/data')
if (isMyType(data)) {
// Now TypeScript knows the type
}Problem: Cannot resolve module paths.
Solution:
Check your tsconfig.json:
{
"compilerOptions": {
"moduleResolution": "node",
"esModuleInterop": true,
"resolveJsonModule": true
}
}Problem: Reading/writing many files is slow.
Solutions:
-
Use parallel operations:
// Slow (sequential) for (const file of files) { await readFileUtf8(file) } // Fast (parallel) await Promise.all(files.map(file => readFileUtf8(file)))
-
Limit concurrency for very large sets:
import { PromiseQueue } from '@socketsecurity/lib/promise-queue' const queue = new PromiseQueue(10) await Promise.all(files.map(file => queue.add(() => readFileUtf8(file))))
Problem: Requests take too long.
Solutions:
-
Enable retries with exponential backoff:
await httpJson(url, { retries: 3, retryDelay: 1000, })
-
Reduce timeout for faster failures:
await httpJson(url, { timeout: 5000, // Fail fast after 5s })
-
Use connection pooling (automatically handled by Node.js http agent)
If your issue isn't covered here:
- Check the API documentation for your specific function
- Review the examples in
/docs/examples.md - Search existing GitHub issues: https://github.com/SocketDev/socket-lib/issues
- Create a new issue with:
- Node.js version (
node --version) - Package version
- Minimal code to reproduce
- Full error message and stack trace
- Operating system
- Node.js version (
- Check import path is correct
- Verify package is installed
- Clear cache and reinstall
- Check file/directory permissions
- Ensure you have write access
- Run with appropriate user permissions
- Verify path exists
- Check for typos in path
- Use absolute paths or
path.join()
- Check command exists in PATH
- Verify arguments are correct
- Review stderr for error details
- Validate JSON syntax
- Check for trailing commas
- Ensure file contains valid JSON
- Check for redirect loops
- Increase
maxRedirectsif legitimate - Verify URL is correct
- Increase timeout value
- Add retry logic
- Check network connection