这个 npm 构建如何工作?

How does this npm build work?

https://github.com/apigee-127/swagger-converter

我看到这段代码:

var convert = require('swagger-converter');
var fs = require('fs');
var resourceListing = JSON.parse(fs.readFileSync('/path/to/petstore/index.json').toString());
var apiDeclarations = [ JSON.parse(fs.readFileSync('/path/to/petstore/pet.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/user.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/store.json').toString())
];

var swagger2Document = convert(resourceListing, apiDeclarations);

console.log(JSON.stringify(swagger2Document, null, 2));

我很困惑我应该在这里做什么 运行 这个?我是否启动节点 http 服务器?

到运行您粘贴的文件,只需将代码保存到script.js这样的文件中。然后从命令行(安装了 node)运行 node script.js。这将 运行 文件。这是它正在做的事情的细分:

var convert = require('swagger-converter');

此行引用您链接到的 swagger-converter 模块。该模块旨在让您将 swagger 文档转换为 JSON.

var fs = require('fs');

这一行获取节点内置文件系统模块(简称fs)的引用。当脚本为 运行ning 时,它提供了一个 API 用于与计算机上的文件系统交互。

var resourceListing = JSON.parse(fs.readFileSync('/path/to/petstore/index.json').toString());

这一行可以分解为:

var indexContent = fs.readFileSync('/path/to/petstore/index.json');
JSON.parse(indexContent.toString());

readFileSync returns index.json 文件的内容作为缓冲区对象,调用 .toString() 很容易将其转换为简单的字符串。然后他们将其传递给 JSON.parse,它解析字符串并将其转换为简单的 JavaScript 对象。

Fun Fact: They could have skipped those steps with a simple var resourceListing = require('/path/to/petstore/index.json');. Node knows how to read JSON files and automatically turn them into JavaScript objects. You need only pass the path to require.

var apiDeclarations = [ JSON.parse(fs.readFileSync('/path/to/petstore/pet.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/user.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/store.json').toString())
];

这段代码与 resourceListing 的作用相同,只是它根据那些 JSON 文件创建了一个包含三个 JavaScript 对象的数组。他们也可以在这里使用 require 来节省一些工作。

最后他们使用转换器进行转换,然后他们将该数据记录到您的脚本所在的终端 运行ning。

var swagger2Document = convert(resourceListing, apiDeclarations);
console.log(JSON.stringify(swagger2Document, null, 2));

JSON.stringifyJSON.parse相反。 stringify 将 JavaScript 对象转换为 JSON 字符串,而 parse 将 JSON 字符串转换为 JavaScript 对象。