// Called on Windows when "python" isn't available in the current $PATH. // We're gonna check if "%SystemDrive%\python27\python.exe" exists. function guessPython () { log.verbose('could not find "' + python + '". guessing location') var rootDir = process.env.SystemDrive || 'C:\\' if (rootDir[rootDir.length - 1] !== '\\') { rootDir += '\\' } var pythonPath = path.resolve(rootDir, 'Python27', 'python.exe') log.verbose('ensuring that file exists:', pythonPath) fs.stat(pythonPath, function (err, stat) { if (err) { if (err.code == 'ENOENT') { failNoPython() } else { callback(err) } return } python = pythonPath checkPythonVersion() }) }
/** * Wrapper around fs.stat which decides how to process a given leaf. * * * @param {String} pathSource for runOp action. * @param {String} pathTarget for runOp action. * @private */ function stat(pathSource, pathTarget) { debug('stat', pathSource, pathTarget); // stat the leaf fs.stat(pathSource, function(err, stat) { if (handleError(err)) return; // deal with the file vs directory handlers. if (stat.isFile()) { traverse.handleFile(pathSource, pathTarget, runOp); } else if(stat.isDirectory()) { traverse.handleDirectory(pathSource, pathTarget, runOp); } // remove a pending item from the stack. --pending; // maybe we are done now? checkComplete(); }); }
ProxyReader.prototype._stat = function () { var me = this , props = me.props // stat the thing to see what the proxy should be. , stat = props.follow ? "stat" : "lstat" fs[stat](props.path, function (er, current) { var type if (er || !current) { type = "File" } else { type = getType(current) } props[type] = true props.type = me.type = type me._old = current me._addProxy(Reader(props, current)) }) }
async.each(contents, function (file, cb) { var filePath = directory + '/' + file; var fileExtension = path.extname(file); fs.stat(filePath, function (err, stat) { // If the file is a directory if (stat && stat.isDirectory()) { // Dive into the directory dive(filePath, extension, action, callback); } else { // Do the action if (fileExtension === extension) action(null, filePath); // Tell async this function is done cb(); } }); }, function (err) {
argv._.forEach(function(arg) { var absPath = path.resolve(arg); fs.stat(absPath, function(err, stat) { if (err) { throw err; } if (stat.isFile()) { transformFile(absPath); } else if (stat.isDirectory()) { var exclude = null; if (argv.exclude) { exclude = new RegExp(argv.exclude); } transformDir(absPath, exclude); } else { throw new Error('Unknown filesystem node type: ' + absPath); } }); });
mkdirp(dir, function() { fs.stat(to, function(statError) { if(!statError && options.overwrite !== true) { return callback(new Error('File '+to+' exists')); } var fromFile = fs.createReadStream(from), toFile = fs.createWriteStream(to), err, onError = function (e) { err = e; }; fromFile.on('error', onError); toFile.on('error', onError); fromFile.once('end', function() { callback(err); }); fromFile.pipe(toFile); }); });
async.forEach(files, function(item, next){ var dest = target + item; fs.stat(dest, function(err, stats){ if (err) throw err; if (stats.isDirectory()){ empty(dest, exclude[item], function(){ fs.readdir(dest, function(err, files){ if (err) throw err; if (files.length === 0) fs.rmdir(dest, next); else next(); }); }); } else { if (arr.indexOf(item) === -1) fs.unlink(dest, next); else next(); } }); }, callback);
return new Promise(function stat (resolve) { if (options.mode && options.chown) resolve() else { // Either mode or chown is not explicitly set // Default behavior is to copy it from original file fs.stat(truename, function (err, stats) { if (err || !stats) resolve() else { options = Object.assign({}, options) if (options.mode == null) { options.mode = stats.mode } if (options.chown == null && process.getuid) { options.chown = { uid: stats.uid, gid: stats.gid } } resolve() } }) } })
function procError (er) { if (er) { log.info('lifecycle', logid(pkg, stage), 'Failed to exec ' + stage + ' script') er.message = pkg._id + ' ' + stage + ': `' + cmd + '`\n' + er.message if (er.code !== 'EPERM') { er.code = 'ELIFECYCLE' } fs.stat(npm.dir, function (statError, d) { if (statError && statError.code === 'ENOENT' && npm.dir.split(path.sep).slice(-1)[0] === 'node_modules') { log.warn('', 'Local package.json exists, but node_modules missing, did you mean to install?') } }) er.pkgid = pkg._id er.stage = stage er.script = cmd er.pkgname = pkg.name } process.removeListener('SIGTERM', procKill) return cb(er) }
function guessMsbuild () { log.verbose('could not find "msbuild.exe". guessing location') // This is basically just hard-coded. If this causes problems // then we'll think of something more clever. var windir = process.env.WINDIR || process.env.SYSTEMROOT || 'C:\\WINDOWS' , frameworkDir = path.resolve(windir, 'Microsoft.NET', 'Framework') , versionDir = path.resolve(frameworkDir, 'v4.0.30319') // This is probably the most brittle part... , msbuild = path.resolve(versionDir, 'msbuild.exe') fs.stat(msbuild, function (err, stat) { if (err) { if (err.code == 'ENOENT') { callback(new Error('Can\'t find "msbuild.exe". Do you have Microsoft Visual Studio C++ 2010 installed?')) } else { callback(err) } return } command = msbuild copyNodeLib() }) }
ProxyReader.prototype._stat = function () { var self = this var props = self.props // stat the thing to see what the proxy should be. var stat = props.follow ? 'stat' : 'lstat' fs[stat](props.path, function (er, current) { var type if (er || !current) { type = 'File' } else { type = getType(current) } props[type] = true props.type = self.type = type self._old = current self._addProxy(Reader(props, current)) }) }
(function next() { var file = list[i++]; if (!file) return done(null, results); file = dir + '/' + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { walk(file, function(err, res) { results = results.concat(res); next(); }); } else { var ext = file.split("."); ext = ext[ext.length - 1]; if (ext.match(SUPPORTED_FILETYPES)) { results.push(file); } next(); } }); })();
files.forEach(function(file) { if (!_this.options.ignoreInitial) { fs.stat(file, function(error, stats) { if (error != null) return _this._emitError(error); if (stats.isDirectory()) { recursiveReaddir(file, function(error, dirFiles) { if (error != null) return _this._emitError(error); dirFiles .filter(function(path) { return !_this._isIgnored(path); }) .forEach(handle); }); } else { handle(file); } }); } _this._watchWithFsEvents(file); });
CachingRegistryClient.prototype.get = function get (uri, params, cb) { assert(typeof uri === "string", "must pass registry URI to get") assert(params && typeof params === "object", "must pass params to get") assert(typeof cb === "function", "must pass callback to get") var parsed = url.parse(uri) assert( parsed.protocol === "http:" || parsed.protocol === "https:", "must have a URL that starts with http: or https:" ) var cacheBase = cacheFile(npm.config.get("cache"))(uri) var cachePath = path.join(cacheBase, ".cache.json") // If the GET is part of a write operation (PUT or DELETE), then // skip past the cache entirely, but still save the results. if (uri.match(/\?write=true$/)) return get_.call(this, uri, cachePath, params, cb) var client = this fs.stat(cachePath, function (er, stat) { if (!er) { fs.readFile(cachePath, function (er, data) { try { data = JSON.parse(data) } catch (ex) { data = null } params.stat = stat params.data = data get_.call(client, uri, cachePath, params, cb) }) } else { get_.call(client, uri, cachePath, params, cb) } }) }
function makeCacheDir (cb) { if (!process.getuid) return mkdir(npm.cache, function (er) { return cb(er, {}) }) var uid = +process.getuid() , gid = +process.getgid() if (uid === 0) { if (process.env.SUDO_UID) uid = +process.env.SUDO_UID if (process.env.SUDO_GID) gid = +process.env.SUDO_GID } if (uid !== 0 || !process.env.HOME) { cacheStat = {uid: uid, gid: gid} return mkdir(npm.cache, afterMkdir) } fs.stat(process.env.HOME, function (er, st) { if (er) { log.error("makeCacheDir", "homeless?") return cb(er) } cacheStat = st log.silly("makeCacheDir", "cache dir uid, gid", [st.uid, st.gid]) return mkdir(npm.cache, afterMkdir) }) function afterMkdir (er, made) { if (er || !cacheStat || isNaN(cacheStat.uid) || isNaN(cacheStat.gid)) { return cb(er, cacheStat) } if (!made) return cb(er, cacheStat) // ensure that the ownership is correct. chownr(made, cacheStat.uid, cacheStat.gid, function (er) { return cb(er, cacheStat) }) } }
fs.readdir(from, stack.add(function(err, dirs) { if (!dirs.length) { results[from] = true; fs.stat(from, stack.add(function(err, stat) { /*istanbul ignore next*/ if (err) { return errors.push(err); } options.stats[from] = stat; options.toHash[from] = path.join(options.to, path.relative(options.from, from)); })); } dirs.forEach(function (dir) { var base = path.join(from, dir); fs.stat(base, stack.add(function(err, stat) { options.stats[base] = stat; options.toHash[base] = path.join(options.to, path.relative(options.from, base)); /*istanbul ignore next*/ if (err) { return errors.push(err); } if (stat.isDirectory()) { getTree(base, options, stack.add(function(errs, tree) { /*istanbul ignore next*/ if (errs && errs.length) { errs.forEach(function(item) { errors.push(item); }); } //tree is always an Array tree.forEach(function(item) { results[item] = true; }); })); } else { results[base] = true; } })); }); }));
function checkGit (localData, cb) { fs.stat(path.join(npm.localPrefix, '.git'), function (er, s) { var doGit = !er && npm.config.get('git-tag-version') if (!doGit) { if (er) log.verbose('version', 'error checking for .git', er) log.verbose('version', 'not tagging in git') return cb(null, false) } // check for git git.whichAndExec( [ 'status', '--porcelain' ], { env: process.env }, function (er, stdout) { if (er && er.code === 'ENOGIT') { log.warn( 'version', 'This is a Git checkout, but the git command was not found.', 'npm could not create a Git tag for this release!' ) return cb(null, false) } var lines = stdout.trim().split('\n').filter(function (line) { return line.trim() && !line.match(/^\?\? /) }).map(function (line) { return line.trim() }) if (lines.length && !npm.config.get('force')) { return cb(new Error( 'Git working directory not clean.\n' + lines.join('\n') )) } localData.hasGit = true cb(null, true) } ) }) }
function explore (args, cb) { if (args.length < 1 || !args[0]) return cb(explore.usage) var p = args.shift() args = args.join(" ").trim() if (args) args = ["-c", args] else args = [] var editor = npm.config.get("editor") , cwd = path.resolve(npm.dir, p) fs.stat(cwd, function (er, s) { if (er || !s.isDirectory()) return cb(new Error( "It doesn't look like "+p+" is installed.")) if (!args.length) console.log( "\nExploring "+cwd+"\n"+ "Type 'exit' or ^D when finished\n") exec(npm.config.get("shell"), args, null, true, cwd, function (er) { // only fail if non-interactive. if (!args.length) return cb() cb(er) }) }) }
function checkGit (cb) { fs.stat(path.join(npm.localPrefix, ".git"), function (er, s) { var doGit = !er && s.isDirectory() && npm.config.get("git-tag-version") if (!doGit) { if (er) log.verbose("version", "error checking for .git", er) log.verbose("version", "not tagging in git") return cb(null, false) } // check for git git.whichAndExec( [ "status", "--porcelain" ], { env : process.env }, function (er, stdout) { if (er && er.code === "ENOGIT") { log.warn( "version", "This is a Git checkout, but the git command was not found.", "npm could not create a Git tag for this release!" ) return cb(null, false) } var lines = stdout.trim().split("\n").filter(function (line) { if (line.match(/^\?\? /)) return false if (line.match(/^. /)) return false return !!line.trim() }).map(function (line) { return line.trim() }) if (lines.length) return cb(new Error( "Git working directory not clean.\n"+lines.join("\n") )) cb(null, true) } ) }) }
function addLocal (p, name, cb_) { if (typeof cb_ !== "function") cb_ = name, name = "" function cb (er, data) { if (er) { // if it doesn't have a / in it, it might be a // remote thing. if (p.indexOf("/") === -1 && p.charAt(0) !== ".") { return addNamed(p, "", cb_) } return log.er(cb_, "Could not install: "+p)(er) } return cb_(er, data) } // figure out if this is a folder or file. fs.stat(p, function (er, s) { if (er) return cb(er) if (s.isDirectory()) addLocalDirectory(p, name, cb) else addLocalTarball(p, name, cb) }) }
Glob.prototype._stat = function (f, cb) { assert(this instanceof Glob) var abs = f if (f.charAt(0) === "/") { abs = path.join(this.root, f) } else if (this.changedCwd) { abs = path.resolve(this.cwd, f) } if (f.length > this.maxLength) { var er = new Error("Path name too long") er.code = "ENAMETOOLONG" er.path = f return this._afterStat(f, abs, cb, er) } this.log('stat', [this.cwd, f, '=', abs]) if (!this.stat && this.cache.hasOwnProperty(f)) { var exists = this.cache[f] , isDir = exists && (Array.isArray(exists) || exists === 2) if (this.sync) return cb.call(this, !!exists, isDir) return process.nextTick(cb.bind(this, !!exists, isDir)) } var stat = this.statCache[abs] if (this.sync || stat) { var er try { stat = fs.statSync(abs) } catch (e) { er = e } this._afterStat(f, abs, cb, er, stat) } else { fs.stat(abs, this._afterStat.bind(this, f, abs, cb)) } }
fs.readdir(from, stack.add(function(err, dirs) { if (!dirs.length) { results[from] = true; fs.stat(from, stack.add(function(err, stat) { if (err) { return errors.push(err); } options.stats[from] = stat; options.toHash[from] = path.join(options.to, path.relative(options.from, from)); })); } dirs.forEach(function (dir) { var base = path.join(from, dir); fs.stat(base, stack.add(function(err, stat) { options.stats[base] = stat; options.toHash[base] = path.join(options.to, path.relative(options.from, base)); if (err) { return errors.push(err); } if (stat.isDirectory()) { getTree(base, options, stack.add(function(errs, tree) { if (errs && errs.length) { errs.forEach(function(item) { errors.push(item); }); } if (tree && tree.length) { tree.forEach(function(item) { results[item] = true; }); } })); } else if (stat.isFile()) { results[base] = true; } })); }); }));
const checkStats = () => { if(this.closed) return; this._activeEvents.set(filename, false); const filePath = path.join(this.path, filename); fs.stat(filePath, (err, stats) => { if(this.closed) return; if(this._activeEvents.get(filename) === true) { process.nextTick(checkStats); return; } this._activeEvents.delete(filename); // ENOENT happens when the file/directory doesn't exist // EPERM happens when the containing directory doesn't exist if(err) { if(err.code !== "ENOENT" && err.code !== "EPERM" && err.code !== "EBUSY") { this.onStatsError(err); } else { if(filename === path.basename(this.path)) { // This may indicate that the directory itself was removed if(!fs.existsSync(this.path)) { this.onDirectoryRemoved(); } } } } this.lastWatchEvent = Date.now(); if(!stats) { this.setMissing(filePath, false, eventType); } else if(stats.isDirectory()) { this.setDirectory(filePath, +stats.mtime || +stats.ctime || 1, false, eventType); } else { if(stats.mtime) { ensureFsAccuracy(stats.mtime); } this.setFileTime(filePath, +stats.mtime || +stats.ctime || 1, false, false, eventType); } }); };
function saveShrinkwrap (tree, next) { validate('OF', arguments) var saveTarget = path.resolve(tree.path, 'npm-shrinkwrap.json') fs.stat(saveTarget, function (er, stat) { if (er) return next() var save = npm.config.get('save') var saveDev = npm.config.get('save-dev') var saveOptional = npm.config.get('save-optional') var shrinkwrap = tree.package._shrinkwrap || {dependencies: {}} var shrinkwrapHasAnyDevOnlyDeps = tree.requires.some(function (dep) { var name = moduleName(dep) return isDevDep(tree, name) && shrinkwrap.dependencies[name] != null }) if (!saveOptional && saveDev && !shrinkwrapHasAnyDevOnlyDeps) return next() if (saveOptional || !save) return next() var silent = false createShrinkwrap(tree.path, tree.package, shrinkwrapHasAnyDevOnlyDeps, silent, next) }) }
utils.mkdir(path.dirname(dst), () => { fs.stat(dst, err => { if (err && err.code === "ENOENT") { const ws = fs.createWriteStream(dst, {mode: "644"}); ws.on("error", onWriteError); file.pipe(ws); } else if (!err) { if (req.query.rename === "1") { utils.getNewPath(dst, newDst => { const ws = fs.createWriteStream(newDst, {mode: "644"}); ws.on("error", onWriteError); file.pipe(ws); }); } else { const ws = fs.createWriteStream(dst, {mode: "644"}); ws.on("error", onWriteError); file.pipe(ws); } } else { onWriteError(err); } }); });
function _parseOverlays(req, res, next) { var overlayDir = overlays[req.query.overlay]; if (overlayDir) { log.silly("FsBase#_parseOverlays()", "checking for overlay='" + req.query.overlay + "' files..."); // We cannot use express.static(), because it would serve // designer files always from the same mount-point in // the '/file' tree. var filePath = path.join(overlayDir, path.basename(req.params.path)); fs.stat(filePath, (function(err, stats) { if (err) { next(err); } else if (stats.isFile()) { log.silly("FsBase#_parseOverlays()", "found overlay file:", filePath); res.status(200); res.sendfile(filePath); } else { next(); } }).bind(this)); } else { setImmediate(next); } }
updateStat: function(post, name, callback){ var source = path.join(post.asset_dir, name), self = this; fs.stat(source, function(err, stats){ if (err) return callback(err); var data = self.findOne({post: post._id, name: name}), mtime = stats.mtime.getTime(); if (data){ data.mtime = mtime; data.modified = data.mtime !== mtime; data.save(); callback(null, data); } else { self.insert({name: name, post: post._id, mtime: mtime, modified: true}, function(data){ callback(null, data); }); } }); }
function runHookLifecycle (pkg, env, wd, unsafe, cb) { // check for a hook script, run if present. var stage = env.npm_lifecycle_event , hook = path.join(npm.dir, ".hooks", stage) , user = unsafe ? null : npm.config.get("user") , group = unsafe ? null : npm.config.get("group") , cmd = hook fs.stat(hook, function (er) { if (er) return cb() exec( "sh", ["-c", cmd], env, true, wd , user, group , function (er) { if (er) { er.message += "\nFailed to exec "+stage+" hook script" log.info(pkg._id, er) } if (npm.ROLLBACK) return cb() cb(er) }) }) }
function runHookLifecycle (pkg, env, wd, unsafe, cb) { // check for a hook script, run if present. var stage = env.npm_lifecycle_event , hook = path.join(npm.dir, ".hooks", stage) , user = unsafe ? null : npm.config.get("user") , group = unsafe ? null : npm.config.get("group") , cmd = hook fs.stat(hook, function (er) { if (er) return cb() var conf = { cwd: wd, env: env, customFds: [ 0, 1, 2] } var proc = spawn("sh", ["-c", cmd], conf) proc.on("close", function (er) { if (er) { er.message += "\nFailed to exec "+stage+" hook script" log.info(pkg._id, er) } if (npm.ROLLBACK) return cb() cb(er) }) }) }
function get (project, version, timeout, nofollow, staleOk, cb) { if (typeof cb !== "function") cb = staleOk, staleOk = false if (typeof cb !== "function") cb = nofollow, nofollow = false if (typeof cb !== "function") cb = timeout, timeout = -1 if (typeof cb !== "function") cb = version, version = null if (typeof cb !== "function") cb = project, project = null if (typeof cb !== "function") { throw new Error("No callback provided to registry.get") } if ( process.env.COMP_CWORD !== undefined && process.env.COMP_LINE !== undefined && process.env.COMP_POINT !== undefined ) timeout = Math.max(timeout, 60000) var uri = [] uri.push(project || "") if (version) uri.push(version) uri = uri.join("/") // /-/all is special. // It uses timestamp-based caching and partial updates, // because it is a monster. if (uri === "/-/all") { return requestAll(cb) } var cache = path.join(npm.cache, uri, ".cache.json") fs.stat(cache, function (er, stat) { if (!er) fs.readFile(cache, function (er, data) { try { data = JSON.parse(data) } catch (ex) { data = null } get_(uri, timeout, cache, stat, data, nofollow, staleOk, cb) }) else get_(uri, timeout, cache, null, null, nofollow, staleOk, cb) }) }