import * as fs from "fs";
const image1 = Media.addImage(document, fs.readFileSync("new.png"));
我的tsconfig.json看起来像:
"compileOnSave": false,
"compilerOptions": {
"importHelpers": true,
"outDir": "./dist/out-tsc",
"sourceMap": false,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
],
"module": "commonjs",
},
"include": [
"src/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
我正在使用fs使用Docx在我的Word文档中添加图像文件,链接:https://docx.js.org/#/usage/images
但是导入时出现错误,请给我解决方案。
错误:错误TypeError:fs__WEBPACK_IMPORTED_MODULE_1 __。readFileSync不是函数
如以上注释中所述,您不能使用JavaScript来从浏览器直接访问文件系统以确保安全。
至少对于您要执行的操作,替代方法是使用类型为“文件”的输入,并在事件触发后读取内容。
这样,在HTML中,您将拥有:
<input type="file" (change)="onFileChanged($event)" accept="image/png, image/jpeg">
在JS端,您将拥有onFileChanged方法:
onFileChanged(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
const result = e.target.result;
// The content of result will depend on what method you invoke on
// reader instance.
console.log(e.target.result)
};
reader.readAsText(file);
// reader.readAsArrayBuffer(file);
// reader.readAsBinaryString(file);
}
您必须根据需要完成实现...但是这是您能够从文件系统读取文件内容所需要的。
有关此内容和FileReader中方法的更多信息,可以转到这里:https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onload