AgentSheet
Back
🟒

Node.js

runtimebackendjavascript

Core Modules

ModulePurpose
fsFile system operations (sync/async)
pathPath manipulation (join, resolve, extname)
httpHTTP server/client
urlURL parsing (parse, format)
osOS info (platform, cpus, freemem)
eventsEventEmitter pattern
cryptoHashing, encryption
child_processSpawn subprocesses (exec, spawn)
streamReadable/Writable streams
const fs = require('fs');
const path = require('path');
const { EventEmitter } = require('events');

Async Patterns

PatternExample
Callbackfs.readFile('f.txt', (err, data) => {})
Promisefs.promises.readFile('f.txt').then(...)
async/awaitconst data = await fs.promises.readFile('f.txt')
EventEmitteremitter.on('event', fn) / emitter.emit('event')
// EventEmitter
const ee = new EventEmitter();
ee.on('data', (d) => console.log(d));
ee.emit('data', 'hello');

File System Operations

OperationSyncAsync
Read filefs.readFileSync(path)fs.readFile(path, callback)
Write filefs.writeFileSync(path, data)fs.writeFile(path, data, callback)
Read dirfs.readdirSync(path)fs.readdir(path, callback)
Statsfs.statSync(path)fs.stat(path, callback)
Watchβ€”fs.watch(path, (ev, name) => {})
// Streams
const rs = fs.createReadStream('in.txt');
const ws = fs.createWriteStream('out.txt');
rs.pipe(ws);

HTTP Server Basics

const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello');
});
server.listen(3000);
MethodPurpose
req.urlRequest path
req.methodGET, POST, etc.
res.writeHead(status, headers)Set response headers
res.end(body)Send and close

Process & Environment

ItemPurpose
process.envEnvironment variables
process.argvCLI args [node, script, ...]
process.exit(code)Exit with code (0=ok)
process.cwd()Current working directory
process.platform'darwin', 'win32', etc.
const [,, arg1, arg2] = process.argv;
const port = process.env.PORT || 3000;

npm Commands

CommandPurpose
npm initCreate package.json
npm init -yInit with defaults
npm installInstall deps
npm install pkgAdd dependency
npm install -D pkgAdd devDependency
npm run <script>Run script from package.json
npm publishPublish to registry
npm linkLink local package globally
npm outdatedCheck outdated deps
npm auditSecurity audit

package.json Fields

FieldPurpose
namePackage name
versionSemver (e.g. 1.0.0)
mainEntry point
scriptsnpm run scripts
dependenciesProd deps
devDependenciesDev deps
type"module" for ESM
exportsConditional exports

Module System

StyleSyntax
CommonJSconst x = require('x') / module.exports = x
ES Modulesimport x from 'x' / export default x
// CommonJS
module.exports = { foo, bar };
exports.foo = foo;

// ESM (package.json: "type": "module")
export default fn;
export { a, b };

Error Handling

// Callback: err first
fs.readFile('f.txt', (err, data) => {
  if (err) return console.error(err);
  console.log(data);
});

// async/await: try/catch
try {
  const data = await fs.promises.readFile('f.txt');
} catch (err) {
  console.error(err);
}

Useful Globals

GlobalPurpose
BufferBinary data
__dirnameDir of current module (CJS)
__filenamePath of current module (CJS)
setTimeout(fn, ms)Run after delay
setInterval(fn, ms)Run repeatedly
clearTimeout(id)Cancel timeout
consolelog, error, warn, etc.
globalGlobal object
// Buffer
Buffer.from('hello');
Buffer.alloc(10);

// __dirname in ESM: use import.meta.url
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));