【问题标题】:Node.js - Cannot read property 'toString' of null when running package on WindowsNode.js - 在 Windows 上运行包时无法读取 null 的属性“toString”
【发布时间】:2016-07-19 18:34:05
【问题描述】:

我正在使用 node.js 上的 gulphercule 包来转换一些纯文本文件。在 Unix 上,一切似乎都运行良好。但是,一些同事在 Windows 上运行它时遇到问题。只有在 Windows 上运行时,它们才会收到以下错误消息:

[13:02:01] TypeError: Cannot read property 'toString' of null at Object.transcludeStringSync (D:\project\node_modules\hercule\lib\hercule.js:136:36)

我已经用hercule@3.0.5hercule@2.0.5 尝试了上述方法,两个包都给出了上述错误。但是,鉴于这仅发生在 Windows 和软件包的多个版本中,我怀疑此问题 与 Node.js 安装或路径有关

使用hercule包的代码:

var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var drakov = require('drakov');
var hercule = require('hercule');

gulp.task('mock', ['i18n','build_minify_no_tests'], function() {
    var mockSpecificationTemplate= fs.readFileSync('test/mock/mock-template.apib','utf8');
    var transcludedMockSpecification = hercule.transcludeStringSync(mockSpecificationTemplate, {
        relativePath: path.resolve('../../../')
    });
    fs.writeFileSync('test/mock/mock.apib', transcludedMockSpecification, 'utf-8');

    // Running mock server
    var drakovArgv = {
        sourceFiles: 'test/mock/mock.apib',
        serverPort: 9000,
        staticPaths: [
            '../../'
        ],
        discover: true,
        watch: true
    };
    drakov.run(drakovArgv);
});

nodenpm版本信息:

$ node -v
v6.3.0
$ npm -v
3.10.3

【问题讨论】:

  • 问题可能是transcludeStringSync 将尝试使用child_process 生成另一个节点进程,并且由于知道的路径或参数,这可能会在 Windows 上失败。无论如何,这是不好的做法,只需使用transcludeString,它应该被修复。
  • 它正在尝试将文件内容转换为String()。但它变得空,因此问题是文件路径没有返回任何东西。你能显示 test/mock/mock-template.apib 内容吗?我认为那里的路径(从 linux 到 Windows)有问题,相对路径 + 这些路径配置不正确。

标签: javascript node.js windows npm installation


【解决方案1】:

hercule.transcludeStringSync 只是运行另一个hercule 进程并向其发送输入:

const result = childProcess.spawnSync('../bin/hercule', syncArgs, syncOptions);

使用脚本../bin/hercule:

#!/usr/bin/env node

"use strict";

require('../lib/main.js');

...显然不能在 Windows 上运行

如果该任务必须同步,您可以改用以下函数:

function transcludeStringSync(input, options) {
  const {dirname, join} = require('path')
  const hercule = join(dirname(require.resolve('hercule')), 'main')
  const args = [hercule, '--reporter', 'json-err']
  for (let name in options) {
    args.push(`--${name}`, `--${options[name]}`)
  }
  const result = require('child_process').spawnSync('node', args, {input})
  const err = result.stderr.toString()
  if (err) throw new Error('Could not transclude input')

  return result.stdout.toString()
}

【讨论】:

  • 这(以及 Windows 行尾的组合)解决了这个问题。接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多