55
66import * as path from 'path' ;
77import { JsonFile } from './JsonFile' ;
8- import { IPackageJson } from './IPackageJson' ;
8+ import { IPackageJson , INodePackageJson } from './IPackageJson' ;
99import { FileConstants } from './Constants' ;
1010import { FileSystem } from './FileSystem' ;
1111
@@ -177,6 +177,18 @@ export class PackageJsonLookup {
177177 return this . loadPackageJson ( packageJsonFilePath ) ;
178178 }
179179
180+ /**
181+ * This function is similar to {@link tryLoadPackageJsonFor}, except that it does not report an error if the
182+ * `version` field is missing from the package.json file.
183+ */
184+ public tryLoadNodePackageJsonFor ( fileOrFolderPath : string ) : INodePackageJson | undefined {
185+ const packageJsonFilePath : string | undefined = this . tryGetPackageJsonFilePathFor ( fileOrFolderPath ) ;
186+ if ( ! packageJsonFilePath ) {
187+ return undefined ;
188+ }
189+ return this . loadNodePackageJson ( packageJsonFilePath ) ;
190+ }
191+
180192 /**
181193 * Loads the specified package.json file, if it is not already present in the cache.
182194 *
@@ -189,6 +201,21 @@ export class PackageJsonLookup {
189201 * @param jsonFilename - a relative or absolute path to a package.json file
190202 */
191203 public loadPackageJson ( jsonFilename : string ) : IPackageJson {
204+ const packageJson : INodePackageJson = this . loadNodePackageJson ( jsonFilename ) ;
205+
206+ if ( ! packageJson . version ) {
207+ throw new Error ( `Error reading "${ jsonFilename } ":\n `
208+ + 'The required field "version" was not found' ) ;
209+ }
210+
211+ return packageJson as IPackageJson ;
212+ }
213+
214+ /**
215+ * This function is similar to {@link loadPackageJson}, except that it does not report an error if the
216+ * `version` field is missing from the package.json file.
217+ */
218+ public loadNodePackageJson ( jsonFilename : string ) : INodePackageJson {
192219 if ( ! FileSystem . exists ( jsonFilename ) ) {
193220 throw new Error ( `Input file not found: ${ jsonFilename } ` ) ;
194221 }
0 commit comments